Skip to content

Commit 788cb8d

Browse files
addisonlynchproost
authored andcommitted
CLN: Use ABC classes for isinstance checks, remove unnecessary imports (pandas-dev#28158)
* CLN: Use ABC classes for isinstance checks, remove unnecessary imports * Formatting repairs
1 parent 74f7b50 commit 788cb8d

File tree

2 files changed

+32
-35
lines changed

2 files changed

+32
-35
lines changed

pandas/core/frame.py

+11-16
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,7 @@
8686
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin as DatetimeLikeArray
8787
from pandas.core.arrays.sparse import SparseFrameAccessor
8888
from pandas.core.generic import NDFrame, _shared_docs
89-
from pandas.core.index import (
90-
Index,
91-
MultiIndex,
92-
ensure_index,
93-
ensure_index_from_sequences,
94-
)
89+
from pandas.core.index import Index, ensure_index, ensure_index_from_sequences
9590
from pandas.core.indexes import base as ibase
9691
from pandas.core.indexes.datetimes import DatetimeIndex
9792
from pandas.core.indexes.multi import maybe_droplevels
@@ -1734,7 +1729,7 @@ def to_records(
17341729
if is_datetime64_any_dtype(self.index) and convert_datetime64:
17351730
ix_vals = [self.index.to_pydatetime()]
17361731
else:
1737-
if isinstance(self.index, MultiIndex):
1732+
if isinstance(self.index, ABCMultiIndex):
17381733
# array of tuples to numpy cols. copy copy copy
17391734
ix_vals = list(map(np.array, zip(*self.index.values)))
17401735
else:
@@ -1745,7 +1740,7 @@ def to_records(
17451740
count = 0
17461741
index_names = list(self.index.names)
17471742

1748-
if isinstance(self.index, MultiIndex):
1743+
if isinstance(self.index, ABCMultiIndex):
17491744
for i, n in enumerate(index_names):
17501745
if n is None:
17511746
index_names[i] = "level_%d" % count
@@ -2868,7 +2863,7 @@ def __getitem__(self, key):
28682863
# The behavior is inconsistent. It returns a Series, except when
28692864
# - the key itself is repeated (test on data.shape, #9519), or
28702865
# - we have a MultiIndex on columns (test on self.columns, #21309)
2871-
if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex):
2866+
if data.shape[1] == 1 and not isinstance(self.columns, ABCMultiIndex):
28722867
data = data[key]
28732868

28742869
return data
@@ -3657,7 +3652,7 @@ def reindexer(value):
36573652
elif isinstance(value, DataFrame):
36583653
# align right-hand-side columns if self.columns
36593654
# is multi-index and self[key] is a sub-frame
3660-
if isinstance(self.columns, MultiIndex) and key in self.columns:
3655+
if isinstance(self.columns, ABCMultiIndex) and key in self.columns:
36613656
loc = self.columns.get_loc(key)
36623657
if isinstance(loc, (slice, Series, np.ndarray, Index)):
36633658
cols = maybe_droplevels(self.columns[loc], key)
@@ -3706,7 +3701,7 @@ def reindexer(value):
37063701

37073702
# broadcast across multiple columns if necessary
37083703
if broadcast and key in self.columns and value.ndim == 1:
3709-
if not self.columns.is_unique or isinstance(self.columns, MultiIndex):
3704+
if not self.columns.is_unique or isinstance(self.columns, ABCMultiIndex):
37103705
existing_piece = self[key]
37113706
if isinstance(existing_piece, DataFrame):
37123707
value = np.tile(value, (len(existing_piece.columns), 1))
@@ -4601,7 +4596,7 @@ def _maybe_casted_values(index, labels=None):
46014596
new_index = self.index.droplevel(level)
46024597

46034598
if not drop:
4604-
if isinstance(self.index, MultiIndex):
4599+
if isinstance(self.index, ABCMultiIndex):
46054600
names = [
46064601
n if n is not None else ("level_%d" % i)
46074602
for (i, n) in enumerate(self.index.names)
@@ -4612,7 +4607,7 @@ def _maybe_casted_values(index, labels=None):
46124607
names = [default] if self.index.name is None else [self.index.name]
46134608
to_insert = ((self.index, None),)
46144609

4615-
multi_col = isinstance(self.columns, MultiIndex)
4610+
multi_col = isinstance(self.columns, ABCMultiIndex)
46164611
for i, (lev, lab) in reversed(list(enumerate(to_insert))):
46174612
if not (level is None or i in level):
46184613
continue
@@ -4994,7 +4989,7 @@ def sort_index(
49944989
level, ascending=ascending, sort_remaining=sort_remaining
49954990
)
49964991

4997-
elif isinstance(labels, MultiIndex):
4992+
elif isinstance(labels, ABCMultiIndex):
49984993
from pandas.core.sorting import lexsort_indexer
49994994

50004995
indexer = lexsort_indexer(
@@ -5280,7 +5275,7 @@ def reorder_levels(self, order, axis=0):
52805275
type of caller (new object)
52815276
"""
52825277
axis = self._get_axis_number(axis)
5283-
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
5278+
if not isinstance(self._get_axis(axis), ABCMultiIndex): # pragma: no cover
52845279
raise TypeError("Can only reorder levels on a hierarchical axis.")
52855280

52865281
result = self.copy()
@@ -7784,7 +7779,7 @@ def _count_level(self, level, axis=0, numeric_only=False):
77847779
count_axis = frame._get_axis(axis)
77857780
agg_axis = frame._get_agg_axis(axis)
77867781

7787-
if not isinstance(count_axis, MultiIndex):
7782+
if not isinstance(count_axis, ABCMultiIndex):
77887783
raise TypeError(
77897784
"Can only count levels on hierarchical "
77907785
"{ax}.".format(ax=self._get_axis_name(axis))

pandas/core/indexing.py

+21-19
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@
2222
is_sparse,
2323
)
2424
from pandas.core.dtypes.concat import concat_compat
25-
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
25+
from pandas.core.dtypes.generic import ABCDataFrame, ABCMultiIndex, ABCSeries
2626
from pandas.core.dtypes.missing import _infer_fill_value, isna
2727

2828
import pandas.core.common as com
29-
from pandas.core.index import Index, InvalidIndexError, MultiIndex
29+
from pandas.core.index import Index, InvalidIndexError
3030
from pandas.core.indexers import is_list_like_indexer, length_of_indexer
3131

3232

@@ -172,7 +172,7 @@ def _get_setitem_indexer(self, key):
172172

173173
ax = self.obj._get_axis(0)
174174

175-
if isinstance(ax, MultiIndex) and self.name != "iloc":
175+
if isinstance(ax, ABCMultiIndex) and self.name != "iloc":
176176
try:
177177
return ax.get_loc(key)
178178
except Exception:
@@ -241,7 +241,7 @@ def _has_valid_tuple(self, key: Tuple):
241241
)
242242

243243
def _is_nested_tuple_indexer(self, tup: Tuple):
244-
if any(isinstance(ax, MultiIndex) for ax in self.obj.axes):
244+
if any(isinstance(ax, ABCMultiIndex) for ax in self.obj.axes):
245245
return any(is_nested_tuple(tup, ax) for ax in self.obj.axes)
246246
return False
247247

@@ -329,7 +329,7 @@ def _setitem_with_indexer(self, indexer, value):
329329
# GH 10360, GH 27841
330330
if isinstance(indexer, tuple) and len(indexer) == len(self.obj.axes):
331331
for i, ax in zip(indexer, self.obj.axes):
332-
if isinstance(ax, MultiIndex) and not (
332+
if isinstance(ax, ABCMultiIndex) and not (
333333
is_integer(i) or com.is_null_slice(i)
334334
):
335335
take_split_path = True
@@ -422,7 +422,9 @@ def _setitem_with_indexer(self, indexer, value):
422422

423423
# if we have a partial multiindex, then need to adjust the plane
424424
# indexer here
425-
if len(labels) == 1 and isinstance(self.obj[labels[0]].axes[0], MultiIndex):
425+
if len(labels) == 1 and isinstance(
426+
self.obj[labels[0]].axes[0], ABCMultiIndex
427+
):
426428
item = labels[0]
427429
obj = self.obj[item]
428430
index = obj.index
@@ -495,7 +497,7 @@ def setter(item, v):
495497
# we have an equal len Frame
496498
if isinstance(value, ABCDataFrame):
497499
sub_indexer = list(indexer)
498-
multiindex_indexer = isinstance(labels, MultiIndex)
500+
multiindex_indexer = isinstance(labels, ABCMultiIndex)
499501

500502
for item in labels:
501503
if item in value:
@@ -777,8 +779,8 @@ def _align_frame(self, indexer, df: ABCDataFrame):
777779
# we have a multi-index and are trying to align
778780
# with a particular, level GH3738
779781
if (
780-
isinstance(ax, MultiIndex)
781-
and isinstance(df.index, MultiIndex)
782+
isinstance(ax, ABCMultiIndex)
783+
and isinstance(df.index, ABCMultiIndex)
782784
and ax.nlevels != df.index.nlevels
783785
):
784786
raise TypeError(
@@ -904,7 +906,7 @@ def _getitem_lowerdim(self, tup: Tuple):
904906
ax0 = self.obj._get_axis(0)
905907
# ...but iloc should handle the tuple as simple integer-location
906908
# instead of checking it as multiindex representation (GH 13797)
907-
if isinstance(ax0, MultiIndex) and self.name != "iloc":
909+
if isinstance(ax0, ABCMultiIndex) and self.name != "iloc":
908910
result = self._handle_lowerdim_multi_index_axis0(tup)
909911
if result is not None:
910912
return result
@@ -1004,7 +1006,7 @@ def _getitem_axis(self, key, axis: int):
10041006
if isinstance(key, slice):
10051007
return self._get_slice_axis(key, axis=axis)
10061008
elif is_list_like_indexer(key) and not (
1007-
isinstance(key, tuple) and isinstance(labels, MultiIndex)
1009+
isinstance(key, tuple) and isinstance(labels, ABCMultiIndex)
10081010
):
10091011

10101012
if hasattr(key, "ndim") and key.ndim > 1:
@@ -1017,7 +1019,7 @@ def _getitem_axis(self, key, axis: int):
10171019
key = labels._maybe_cast_indexer(key)
10181020

10191021
if is_integer(key):
1020-
if axis == 0 and isinstance(labels, MultiIndex):
1022+
if axis == 0 and isinstance(labels, ABCMultiIndex):
10211023
try:
10221024
return self._get_label(key, axis=axis)
10231025
except (KeyError, TypeError):
@@ -1228,7 +1230,7 @@ def _convert_to_indexer(self, obj, axis: int, raise_missing: bool = False):
12281230
try:
12291231
return labels.get_loc(obj)
12301232
except LookupError:
1231-
if isinstance(obj, tuple) and isinstance(labels, MultiIndex):
1233+
if isinstance(obj, tuple) and isinstance(labels, ABCMultiIndex):
12321234
if len(obj) == labels.nlevels:
12331235
return {"key": obj}
12341236
raise
@@ -1248,7 +1250,7 @@ def _convert_to_indexer(self, obj, axis: int, raise_missing: bool = False):
12481250
# always valid
12491251
return {"key": obj}
12501252

1251-
if obj >= self.obj.shape[axis] and not isinstance(labels, MultiIndex):
1253+
if obj >= self.obj.shape[axis] and not isinstance(labels, ABCMultiIndex):
12521254
# a positional
12531255
raise ValueError("cannot set by positional indexing with enlargement")
12541256

@@ -1715,7 +1717,7 @@ def _is_scalar_access(self, key: Tuple):
17151717
return False
17161718

17171719
ax = self.obj.axes[i]
1718-
if isinstance(ax, MultiIndex):
1720+
if isinstance(ax, ABCMultiIndex):
17191721
return False
17201722

17211723
if isinstance(k, str) and ax._supports_partial_string_indexing:
@@ -1737,7 +1739,7 @@ def _getitem_scalar(self, key):
17371739
def _get_partial_string_timestamp_match_key(self, key, labels):
17381740
"""Translate any partial string timestamp matches in key, returning the
17391741
new key (GH 10331)"""
1740-
if isinstance(labels, MultiIndex):
1742+
if isinstance(labels, ABCMultiIndex):
17411743
if (
17421744
isinstance(key, str)
17431745
and labels.levels[0]._supports_partial_string_indexing
@@ -1781,7 +1783,7 @@ def _getitem_axis(self, key, axis: int):
17811783
# to a list of keys
17821784
# we will use the *values* of the object
17831785
# and NOT the index if its a PandasObject
1784-
if isinstance(labels, MultiIndex):
1786+
if isinstance(labels, ABCMultiIndex):
17851787

17861788
if isinstance(key, (ABCSeries, np.ndarray)) and key.ndim <= 1:
17871789
# Series, or 0,1 ndim ndarray
@@ -1809,7 +1811,7 @@ def _getitem_axis(self, key, axis: int):
18091811
key = tuple([key])
18101812

18111813
# an iterable multi-selection
1812-
if not (isinstance(key, tuple) and isinstance(labels, MultiIndex)):
1814+
if not (isinstance(key, tuple) and isinstance(labels, ABCMultiIndex)):
18131815

18141816
if hasattr(key, "ndim") and key.ndim > 1:
18151817
raise ValueError("Cannot index with multidimensional key")
@@ -2474,7 +2476,7 @@ def is_nested_tuple(tup, labels):
24742476
for i, k in enumerate(tup):
24752477

24762478
if is_list_like(k) or isinstance(k, slice):
2477-
return isinstance(labels, MultiIndex)
2479+
return isinstance(labels, ABCMultiIndex)
24782480

24792481
return False
24802482

0 commit comments

Comments
 (0)