|
110 | 110 | UInt64Index,
|
111 | 111 | )
|
112 | 112 | from pandas.core.arrays import (
|
| 113 | + BaseMaskedArray, |
113 | 114 | DatetimeArray,
|
| 115 | + ExtensionArray, |
114 | 116 | PandasArray,
|
115 | 117 | PeriodArray,
|
116 | 118 | TimedeltaArray,
|
117 | 119 | period_array,
|
118 | 120 | )
|
| 121 | +from pandas.core.arrays._mixins import NDArrayBackedExtensionArray |
119 | 122 |
|
120 | 123 | if TYPE_CHECKING:
|
121 | 124 | from pandas import (
|
@@ -1050,3 +1053,51 @@ def at(x):
|
1050 | 1053 |
|
1051 | 1054 | def iat(x):
|
1052 | 1055 | return x.iat
|
| 1056 | + |
| 1057 | + |
| 1058 | +# ----------------------------------------------------------------------------- |
| 1059 | + |
| 1060 | + |
| 1061 | +def shares_memory(left, right) -> bool: |
| 1062 | + """ |
| 1063 | + Pandas-compat for np.shares_memory. |
| 1064 | + """ |
| 1065 | + if isinstance(left, np.ndarray) and isinstance(right, np.ndarray): |
| 1066 | + return np.shares_memory(left, right) |
| 1067 | + elif isinstance(left, np.ndarray): |
| 1068 | + # Call with reversed args to get to unpacking logic below. |
| 1069 | + return shares_memory(right, left) |
| 1070 | + |
| 1071 | + if isinstance(left, RangeIndex): |
| 1072 | + return False |
| 1073 | + if isinstance(left, MultiIndex): |
| 1074 | + return shares_memory(left._codes, right) |
| 1075 | + if isinstance(left, (Index, Series)): |
| 1076 | + return shares_memory(left._values, right) |
| 1077 | + |
| 1078 | + if isinstance(left, NDArrayBackedExtensionArray): |
| 1079 | + return shares_memory(left._ndarray, right) |
| 1080 | + if isinstance(left, pd.SparseArray): |
| 1081 | + return shares_memory(left.sp_values, right) |
| 1082 | + |
| 1083 | + if isinstance(left, ExtensionArray) and left.dtype == "string[pyarrow]": |
| 1084 | + # https://github.com/pandas-dev/pandas/pull/43930#discussion_r736862669 |
| 1085 | + if isinstance(right, ExtensionArray) and right.dtype == "string[pyarrow]": |
| 1086 | + left_pa_data = left._data |
| 1087 | + right_pa_data = right._data |
| 1088 | + left_buf1 = left_pa_data.chunk(0).buffers()[1] |
| 1089 | + right_buf1 = right_pa_data.chunk(0).buffers()[1] |
| 1090 | + return left_buf1 == right_buf1 |
| 1091 | + |
| 1092 | + if isinstance(left, BaseMaskedArray) and isinstance(right, BaseMaskedArray): |
| 1093 | + # By convention, we'll say these share memory if they share *either* |
| 1094 | + # the _data or the _mask |
| 1095 | + return np.shares_memory(left._data, right._data) or np.shares_memory( |
| 1096 | + left._mask, right._mask |
| 1097 | + ) |
| 1098 | + |
| 1099 | + if isinstance(left, DataFrame) and len(left._mgr.arrays) == 1: |
| 1100 | + arr = left._mgr.arrays[0] |
| 1101 | + return shares_memory(arr, right) |
| 1102 | + |
| 1103 | + raise NotImplementedError(type(left), type(right)) |
0 commit comments