MCPcopy
hub / github.com/pandas-dev/pandas / compute

Method compute

pandas/core/methods/selectn.py:106–190  ·  view source on GitHub ↗
(self, method: str)

Source from the content-addressed store, hash-verified

104 """
105
106 def compute(self, method: str) -> Series:
107 from pandas.core.reshape.concat import concat
108
109 n = self.n
110 dtype = self.obj.dtype
111 if not self.is_valid_dtype_n_method(dtype):
112 raise TypeError(f"Cannot use method '{method}' with dtype {dtype}")
113
114 if n <= 0:
115 return self.obj[[]]
116
117 # Save index and reset to default index to avoid performance impact
118 # from when index contains duplicates
119 original_index: Index = self.obj.index
120 default_index = self.obj.reset_index(drop=True)
121
122 # Slower method used when taking the full length of the series
123 # In this case, it is equivalent to a sort.
124 if n >= len(default_index):
125 ascending = method == "nsmallest"
126 result = default_index.sort_values(ascending=ascending, kind="stable").head(
127 n
128 )
129 result.index = original_index.take(result.index)
130 return result
131
132 # Fast method used in the general case
133 dropped = default_index.dropna()
134 nan_index = default_index.drop(dropped.index)
135
136 new_dtype = dropped.dtype
137
138 # Similar to algorithms._ensure_data
139 arr = dropped._values
140 if needs_i8_conversion(arr.dtype):
141 arr = arr.view("i8")
142 elif isinstance(arr.dtype, BaseMaskedDtype):
143 arr = arr._data
144 else:
145 arr = np.asarray(arr)
146 if arr.dtype.kind == "b":
147 arr = arr.view(np.uint8)
148
149 if method == "nlargest":
150 arr = -arr
151 if is_integer_dtype(new_dtype):
152 # GH 21426: ensure reverse ordering at boundaries
153 arr -= 1
154
155 elif is_bool_dtype(new_dtype):
156 # GH 26154: ensure False is smaller than True
157 arr = 1 - (-arr)
158
159 if self.keep == "last":
160 arr = arr[::-1]
161
162 nbase = n
163 narr = len(arr)

Callers

nothing calls this directly

Calls 15

needs_i8_conversionFunction · 0.90
is_integer_dtypeFunction · 0.90
is_bool_dtypeFunction · 0.90
concatFunction · 0.90
minFunction · 0.85
nonzeroMethod · 0.80
reset_indexMethod · 0.45
headMethod · 0.45
sort_valuesMethod · 0.45
takeMethod · 0.45
dropnaMethod · 0.45

Tested by

no test coverage detected