Skip to content

Commit 8887b1e

Browse files
jbrockmendeljreback
authored andcommitted
CLN: requested follow-ups (#27332)
1 parent 3885575 commit 8887b1e

File tree

8 files changed

+51
-75
lines changed

8 files changed

+51
-75
lines changed

pandas/core/generic.py

-24
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,6 @@ def _setup_axes(
274274
info_axis=None,
275275
stat_axis=None,
276276
aliases=None,
277-
slicers=None,
278277
axes_are_reversed=False,
279278
build_axes=True,
280279
ns=None,
@@ -288,7 +287,6 @@ def _setup_axes(
288287
info_axis_num : the axis of the selector dimension (int)
289288
stat_axis_num : the number of axis for the default stats (int)
290289
aliases : other names for a single axis (dict)
291-
slicers : how axes slice to others (dict)
292290
axes_are_reversed : boolean whether to treat passed axes as
293291
reversed (DataFrame)
294292
build_axes : setup the axis properties (default True)
@@ -300,7 +298,6 @@ def _setup_axes(
300298
cls._AXIS_ALIASES = aliases or dict()
301299
cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()}
302300
cls._AXIS_NAMES = dict(enumerate(axes))
303-
cls._AXIS_SLICEMAP = slicers or None
304301
cls._AXIS_REVERSED = axes_are_reversed
305302

306303
# typ
@@ -347,15 +344,6 @@ def _construct_axes_dict_from(self, axes, **kwargs):
347344
d.update(kwargs)
348345
return d
349346

350-
def _construct_axes_dict_for_slice(self, axes=None, **kwargs):
351-
"""Return an axes dictionary for myself."""
352-
d = {
353-
self._AXIS_SLICEMAP[a]: self._get_axis(a)
354-
for a in (axes or self._AXIS_ORDERS)
355-
}
356-
d.update(kwargs)
357-
return d
358-
359347
def _construct_axes_from_arguments(
360348
self, args, kwargs, require_all=False, sentinel=None
361349
):
@@ -577,18 +565,6 @@ def _obj_with_exclusions(self):
577565
""" internal compat with SelectionMixin """
578566
return self
579567

580-
def _expand_axes(self, key):
581-
new_axes = []
582-
for k, ax in zip(key, self.axes):
583-
if k not in ax:
584-
if type(k) != ax.dtype.type:
585-
ax = ax.astype("O")
586-
new_axes.append(ax.insert(len(ax), k))
587-
else:
588-
new_axes.append(ax)
589-
590-
return new_axes
591-
592568
def set_axis(self, labels, axis=0, inplace=None):
593569
"""
594570
Assign desired index to given axis.

pandas/core/indexers.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,19 @@ def is_scalar_indexer(indexer, arr_value) -> bool:
3636
return False
3737

3838

39-
def is_empty_indexer(indexer, arr_value) -> bool:
40-
# return a boolean if we have an empty indexer
39+
def is_empty_indexer(indexer, arr_value: np.ndarray) -> bool:
40+
"""
41+
Check if we have an empty indexer.
42+
43+
Parameters
44+
----------
45+
indexer : object
46+
arr_value : np.ndarray
4147
48+
Returns
49+
-------
50+
bool
51+
"""
4252
if is_list_like(indexer) and not len(indexer):
4353
return True
4454
if arr_value.ndim == 1:

pandas/core/indexing.py

+32-41
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,7 @@ def _get_label(self, label, axis=None):
158158

159159
return self.obj._xs(label, axis=axis)
160160

161-
def _get_loc(self, key, axis=None):
162-
if axis is None:
163-
axis = self.axis
161+
def _get_loc(self, key, axis: int):
164162
return self.obj._ixs(key, axis=axis)
165163

166164
def _slice(self, obj, axis=None, kind=None):
@@ -172,11 +170,11 @@ def _get_setitem_indexer(self, key):
172170
if self.axis is not None:
173171
return self._convert_tuple(key, is_setter=True)
174172

175-
axis = self.obj._get_axis(0)
173+
ax = self.obj._get_axis(0)
176174

177-
if isinstance(axis, MultiIndex) and self.name != "iloc":
175+
if isinstance(ax, MultiIndex) and self.name != "iloc":
178176
try:
179-
return axis.get_loc(key)
177+
return ax.get_loc(key)
180178
except Exception:
181179
pass
182180

@@ -189,8 +187,9 @@ def _get_setitem_indexer(self, key):
189187
if isinstance(key, range):
190188
return self._convert_range(key, is_setter=True)
191189

190+
axis = self.axis or 0
192191
try:
193-
return self._convert_to_indexer(key, is_setter=True)
192+
return self._convert_to_indexer(key, axis=axis, is_setter=True)
194193
except TypeError as e:
195194

196195
# invalid indexer type vs 'other' indexing errors
@@ -206,30 +205,27 @@ def __setitem__(self, key, value):
206205
indexer = self._get_setitem_indexer(key)
207206
self._setitem_with_indexer(indexer, value)
208207

209-
def _validate_key(self, key, axis):
208+
def _validate_key(self, key, axis: int):
210209
"""
211210
Ensure that key is valid for current indexer.
212211
213212
Parameters
214213
----------
215214
key : scalar, slice or list-like
216215
The key requested
217-
218216
axis : int
219217
Dimension on which the indexing is being made
220218
221219
Raises
222220
------
223221
TypeError
224222
If the key (or some element of it) has wrong type
225-
226223
IndexError
227224
If the key (or some element of it) is out of bounds
228-
229225
KeyError
230226
If the key was not found
231227
"""
232-
raise AbstractMethodError()
228+
raise AbstractMethodError(self)
233229

234230
def _has_valid_tuple(self, key):
235231
""" check the key for valid keys across my indexer """
@@ -249,7 +245,7 @@ def _is_nested_tuple_indexer(self, tup):
249245
return any(is_nested_tuple(tup, ax) for ax in self.obj.axes)
250246
return False
251247

252-
def _convert_tuple(self, key, is_setter=False):
248+
def _convert_tuple(self, key, is_setter: bool = False):
253249
keyidx = []
254250
if self.axis is not None:
255251
axis = self.obj._get_axis_number(self.axis)
@@ -268,19 +264,17 @@ def _convert_tuple(self, key, is_setter=False):
268264
keyidx.append(idx)
269265
return tuple(keyidx)
270266

271-
def _convert_range(self, key, is_setter=False):
267+
def _convert_range(self, key, is_setter: bool = False):
272268
""" convert a range argument """
273269
return list(key)
274270

275-
def _convert_scalar_indexer(self, key, axis):
271+
def _convert_scalar_indexer(self, key, axis: int):
276272
# if we are accessing via lowered dim, use the last dim
277-
if axis is None:
278-
axis = 0
279273
ax = self.obj._get_axis(min(axis, self.ndim - 1))
280274
# a scalar
281275
return ax._convert_scalar_indexer(key, kind=self.name)
282276

283-
def _convert_slice_indexer(self, key, axis):
277+
def _convert_slice_indexer(self, key, axis: int):
284278
# if we are accessing via lowered dim, use the last dim
285279
ax = self.obj._get_axis(min(axis, self.ndim - 1))
286280
return ax._convert_slice_indexer(key, kind=self.name)
@@ -883,7 +877,7 @@ def _multi_take(self, tup):
883877
}
884878
return o._reindex_with_indexers(d, copy=True, allow_dups=True)
885879

886-
def _convert_for_reindex(self, key, axis=None):
880+
def _convert_for_reindex(self, key, axis: int):
887881
return key
888882

889883
def _handle_lowerdim_multi_index_axis0(self, tup):
@@ -1055,7 +1049,7 @@ def _getitem_axis(self, key, axis=None):
10551049

10561050
return self._get_label(key, axis=axis)
10571051

1058-
def _get_listlike_indexer(self, key, axis, raise_missing=False):
1052+
def _get_listlike_indexer(self, key, axis: int, raise_missing: bool = False):
10591053
"""
10601054
Transform a list-like of keys into a new index and an indexer.
10611055
@@ -1151,7 +1145,9 @@ def _getitem_iterable(self, key, axis: int):
11511145
{axis: [keyarr, indexer]}, copy=True, allow_dups=True
11521146
)
11531147

1154-
def _validate_read_indexer(self, key, indexer, axis, raise_missing=False):
1148+
def _validate_read_indexer(
1149+
self, key, indexer, axis: int, raise_missing: bool = False
1150+
):
11551151
"""
11561152
Check that indexer can be used to return a result (e.g. at least one
11571153
element was found, unless the list of keys was actually empty).
@@ -1216,7 +1212,9 @@ def _validate_read_indexer(self, key, indexer, axis, raise_missing=False):
12161212
if not (ax.is_categorical() or ax.is_interval()):
12171213
warnings.warn(_missing_key_warning, FutureWarning, stacklevel=6)
12181214

1219-
def _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=False):
1215+
def _convert_to_indexer(
1216+
self, obj, axis: int, is_setter: bool = False, raise_missing: bool = False
1217+
):
12201218
"""
12211219
Convert indexing key into something we can use to do actual fancy
12221220
indexing on an ndarray
@@ -1231,9 +1229,6 @@ def _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=Fal
12311229
raise AmbiguousIndexError with integer labels?
12321230
- No, prefer label-based indexing
12331231
"""
1234-
if axis is None:
1235-
axis = self.axis or 0
1236-
12371232
labels = self.obj._get_axis(axis)
12381233

12391234
if isinstance(obj, slice):
@@ -1362,7 +1357,7 @@ def __init__(self, name, obj):
13621357
super().__init__(name, obj)
13631358

13641359
@Appender(_NDFrameIndexer._validate_key.__doc__)
1365-
def _validate_key(self, key, axis):
1360+
def _validate_key(self, key, axis: int):
13661361
if isinstance(key, slice):
13671362
return True
13681363

@@ -1378,7 +1373,7 @@ def _validate_key(self, key, axis):
13781373

13791374
return True
13801375

1381-
def _convert_for_reindex(self, key, axis=None):
1376+
def _convert_for_reindex(self, key, axis: int):
13821377
"""
13831378
Transform a list of keys into a new array ready to be used as axis of
13841379
the object we return (e.g. including NaNs).
@@ -1394,9 +1389,6 @@ def _convert_for_reindex(self, key, axis=None):
13941389
-------
13951390
list-like of labels
13961391
"""
1397-
1398-
if axis is None:
1399-
axis = self.axis or 0
14001392
labels = self.obj._get_axis(axis)
14011393

14021394
if com.is_bool_indexer(key):
@@ -1726,7 +1718,7 @@ class _LocIndexer(_LocationIndexer):
17261718
_exception = KeyError
17271719

17281720
@Appender(_NDFrameIndexer._validate_key.__doc__)
1729-
def _validate_key(self, key, axis):
1721+
def _validate_key(self, key, axis: int):
17301722

17311723
# valid for a collection of labels (we check their presence later)
17321724
# slice of labels (where start-end in labels)
@@ -2006,7 +1998,7 @@ class _iLocIndexer(_LocationIndexer):
20061998
_exception = IndexError
20071999
_get_slice_axis = _NDFrameIndexer._get_slice_axis
20082000

2009-
def _validate_key(self, key, axis):
2001+
def _validate_key(self, key, axis: int):
20102002
if com.is_bool_indexer(key):
20112003
if hasattr(key, "index") and isinstance(key.index, Index):
20122004
if key.index.inferred_type == "integer":
@@ -2132,7 +2124,7 @@ def _getitem_tuple(self, tup):
21322124

21332125
return retval
21342126

2135-
def _get_list_axis(self, key, axis=None):
2127+
def _get_list_axis(self, key, axis: int):
21362128
"""
21372129
Return Series values by list or array of integers
21382130
@@ -2145,8 +2137,6 @@ def _get_list_axis(self, key, axis=None):
21452137
-------
21462138
Series object
21472139
"""
2148-
if axis is None:
2149-
axis = self.axis or 0
21502140
try:
21512141
return self.obj._take(key, axis=axis)
21522142
except IndexError:
@@ -2184,10 +2174,11 @@ def _getitem_axis(self, key, axis=None):
21842174

21852175
return self._get_loc(key, axis=axis)
21862176

2187-
def _convert_to_indexer(self, obj, axis=None, is_setter=False):
2177+
# raise_missing is included for compat with the parent class signature
2178+
def _convert_to_indexer(
2179+
self, obj, axis: int, is_setter: bool = False, raise_missing: bool = False
2180+
):
21882181
""" much simpler as we only have to deal with our valid types """
2189-
if axis is None:
2190-
axis = self.axis or 0
21912182

21922183
# make need to convert a float key
21932184
if isinstance(obj, slice):
@@ -2209,7 +2200,7 @@ def _convert_to_indexer(self, obj, axis=None, is_setter=False):
22092200
class _ScalarAccessIndexer(_NDFrameIndexer):
22102201
""" access scalars quickly """
22112202

2212-
def _convert_key(self, key, is_setter=False):
2203+
def _convert_key(self, key, is_setter: bool = False):
22132204
return list(key)
22142205

22152206
def __getitem__(self, key):
@@ -2289,7 +2280,7 @@ class _AtIndexer(_ScalarAccessIndexer):
22892280

22902281
_takeable = False
22912282

2292-
def _convert_key(self, key, is_setter=False):
2283+
def _convert_key(self, key, is_setter: bool = False):
22932284
""" require they keys to be the same type as the index (so we don't
22942285
fallback)
22952286
"""
@@ -2366,7 +2357,7 @@ class _iAtIndexer(_ScalarAccessIndexer):
23662357
def _has_valid_setitem_indexer(self, indexer):
23672358
self._has_valid_positional_setitem_indexer(indexer)
23682359

2369-
def _convert_key(self, key, is_setter=False):
2360+
def _convert_key(self, key, is_setter: bool = False):
23702361
""" require integer args (and convert to label arguments) """
23712362
for a, i in zip(self.obj.axes, key):
23722363
if not is_integer(i):

pandas/core/internals/blocks.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2249,9 +2249,9 @@ def _can_hold_element(self, element):
22492249
tipo = maybe_infer_dtype_type(element)
22502250
if tipo is not None:
22512251
return tipo == _NS_DTYPE or tipo == np.int64
2252-
if isinstance(element, datetime):
2252+
elif isinstance(element, datetime):
22532253
return element.tzinfo is None
2254-
if is_integer(element):
2254+
elif is_integer(element):
22552255
return element == tslibs.iNaT
22562256

22572257
# TODO: shouldnt we exclude timedelta64("NaT")? See GH#27297
@@ -2607,7 +2607,7 @@ def _can_hold_element(self, element):
26072607
tipo = maybe_infer_dtype_type(element)
26082608
if tipo is not None:
26092609
return issubclass(tipo.type, (np.timedelta64, np.int64))
2610-
if element is NaT:
2610+
elif element is NaT:
26112611
return True
26122612
return is_integer(element) or isinstance(
26132613
element, (timedelta, np.timedelta64, np.int64)

pandas/io/pytables.py

+1
Original file line numberDiff line numberDiff line change
@@ -3974,6 +3974,7 @@ def process_filter(field, filt):
39743974
for axis_name in obj._AXIS_NAMES.values():
39753975
axis_number = obj._get_axis_number(axis_name)
39763976
axis_values = obj._get_axis(axis_name)
3977+
assert axis_number is not None
39773978

39783979
# see if the field is the name of an axis
39793980
if field == axis_name:

pandas/tests/frame/test_indexing.py

+1
Original file line numberDiff line numberDiff line change
@@ -1680,6 +1680,7 @@ def test_setitem_single_column_mixed_datetime(self):
16801680
df.loc["d", :] = np.nan
16811681
assert not isna(df.loc["c", :]).all()
16821682

1683+
# FIXME: don't leave commented-out
16831684
# as of GH 3216 this will now work!
16841685
# try to set with a list like item
16851686
# pytest.raises(

pandas/tests/series/test_operators.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -692,10 +692,7 @@ def test_operators_corner(self):
692692
)
693693
tm.assert_series_equal(added[:-5], expected)
694694

695-
pairings = [
696-
(Series.div, operator.truediv, 1),
697-
(Series.rdiv, lambda x, y: operator.truediv(y, x), 1),
698-
]
695+
pairings = [(Series.div, operator.truediv, 1), (Series.rdiv, ops.rtruediv, 1)]
699696
for op in ["add", "sub", "mul", "pow", "truediv", "floordiv"]:
700697
fv = 0
701698
lop = getattr(Series, op)

pandas/tests/sparse/series/test_series.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,7 @@ def check(a, b):
586586
# FIXME: don't leave commented-out
587587
# NaN ** 0 = 1 in C?
588588
# _check_op(a, b, operator.pow)
589-
# _check_op(a, b, lambda x, y: operator.pow(y, x))
589+
# _check_op(a, b, ops.rpow)
590590

591591
check(self.bseries, self.bseries)
592592
check(self.iseries, self.iseries)

0 commit comments

Comments
 (0)