Skip to content

Commit 75d02c7

Browse files
authored
CLN refactor core indexes (#37582)
1 parent f37c27c commit 75d02c7

File tree

3 files changed

+32
-45
lines changed

3 files changed

+32
-45
lines changed

pandas/core/indexes/api.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,4 @@ def all_indexes_same(indexes):
282282
"""
283283
itr = iter(indexes)
284284
first = next(itr)
285-
for index in itr:
286-
if not first.equals(index):
287-
return False
288-
return True
285+
return all(first.equals(index) for index in itr)

pandas/core/indexes/base.py

+29-35
Original file line numberDiff line numberDiff line change
@@ -907,9 +907,7 @@ def __repr__(self) -> str_t:
907907
if data is None:
908908
data = ""
909909

910-
res = f"{klass_name}({data}{prepr})"
911-
912-
return res
910+
return f"{klass_name}({data}{prepr})"
913911

914912
def _format_space(self) -> str_t:
915913

@@ -988,7 +986,6 @@ def _format_with_header(
988986
if is_object_dtype(values.dtype):
989987
values = lib.maybe_convert_objects(values, safe=1)
990988

991-
if is_object_dtype(values.dtype):
992989
result = [pprint_thing(x, escape_chars=("\t", "\r", "\n")) for x in values]
993990

994991
# could have nans
@@ -1616,7 +1613,7 @@ def _drop_level_numbers(self, levnums: List[int]):
16161613
Drop MultiIndex levels by level _number_, not name.
16171614
"""
16181615

1619-
if len(levnums) == 0:
1616+
if not levnums:
16201617
return self
16211618
if len(levnums) >= self.nlevels:
16221619
raise ValueError(
@@ -3154,7 +3151,7 @@ def _get_indexer(
31543151
target, method=method, limit=limit, tolerance=tolerance
31553152
)
31563153

3157-
if method == "pad" or method == "backfill":
3154+
if method in ["pad", "backfill"]:
31583155
indexer = self._get_fill_indexer(target, method, limit, tolerance)
31593156
elif method == "nearest":
31603157
indexer = self._get_nearest_indexer(target, limit, tolerance)
@@ -3295,8 +3292,7 @@ def _filter_indexer_tolerance(
32953292
) -> np.ndarray:
32963293
# error: Unsupported left operand type for - ("ExtensionArray")
32973294
distance = abs(self._values[indexer] - target) # type: ignore[operator]
3298-
indexer = np.where(distance <= tolerance, indexer, -1)
3299-
return indexer
3295+
return np.where(distance <= tolerance, indexer, -1)
33003296

33013297
# --------------------------------------------------------------------
33023298
# Indexer Conversion Methods
@@ -3426,8 +3422,7 @@ def _convert_arr_indexer(self, keyarr):
34263422
-------
34273423
converted_keyarr : array-like
34283424
"""
3429-
keyarr = com.asarray_tuplesafe(keyarr)
3430-
return keyarr
3425+
return com.asarray_tuplesafe(keyarr)
34313426

34323427
def _convert_list_indexer(self, keyarr):
34333428
"""
@@ -3795,9 +3790,8 @@ def _join_multi(self, other, how, return_indexers=True):
37953790
other, level, how=how, return_indexers=return_indexers
37963791
)
37973792

3798-
if flip_order:
3799-
if isinstance(result, tuple):
3800-
return result[0], result[2], result[1]
3793+
if flip_order and isinstance(result, tuple):
3794+
return result[0], result[2], result[1]
38013795
return result
38023796

38033797
@final
@@ -4329,7 +4323,7 @@ def append(self, other):
43294323
to_concat = [self]
43304324

43314325
if isinstance(other, (list, tuple)):
4332-
to_concat = to_concat + list(other)
4326+
to_concat += list(other)
43334327
else:
43344328
to_concat.append(other)
43354329

@@ -4821,9 +4815,7 @@ def _should_fallback_to_positional(self) -> bool:
48214815
"""
48224816
Should an integer key be treated as positional?
48234817
"""
4824-
if self.holds_integer() or self.is_boolean():
4825-
return False
4826-
return True
4818+
return not self.holds_integer() and not self.is_boolean()
48274819

48284820
def _get_values_for_loc(self, series: "Series", loc, key):
48294821
"""
@@ -5286,11 +5278,7 @@ def _validate_indexer(self, form: str_t, key, kind: str_t):
52865278
"""
52875279
assert kind in ["getitem", "iloc"]
52885280

5289-
if key is None:
5290-
pass
5291-
elif is_integer(key):
5292-
pass
5293-
else:
5281+
if key is not None and not is_integer(key):
52945282
raise self._invalid_indexer(form, key)
52955283

52965284
def _maybe_cast_slice_bound(self, label, side: str_t, kind):
@@ -5609,9 +5597,10 @@ def _cmp_method(self, other, op):
56095597
elif op in {operator.ne, operator.lt, operator.gt}:
56105598
return np.zeros(len(self), dtype=bool)
56115599

5612-
if isinstance(other, (np.ndarray, Index, ABCSeries, ExtensionArray)):
5613-
if len(self) != len(other):
5614-
raise ValueError("Lengths must match to compare")
5600+
if isinstance(other, (np.ndarray, Index, ABCSeries, ExtensionArray)) and len(
5601+
self
5602+
) != len(other):
5603+
raise ValueError("Lengths must match to compare")
56155604

56165605
if not isinstance(other, ABCMultiIndex):
56175606
other = extract_array(other, extract_numpy=True)
@@ -5931,11 +5920,20 @@ def ensure_has_len(seq):
59315920
def trim_front(strings: List[str]) -> List[str]:
59325921
"""
59335922
Trims zeros and decimal points.
5923+
5924+
Examples
5925+
--------
5926+
>>> trim_front([" a", " b"])
5927+
['a', 'b']
5928+
5929+
>>> trim_front([" a", " "])
5930+
['a', '']
59345931
"""
5935-
trimmed = strings
5936-
while len(strings) > 0 and all(x[0] == " " for x in trimmed):
5937-
trimmed = [x[1:] for x in trimmed]
5938-
return trimmed
5932+
if not strings:
5933+
return strings
5934+
while all(strings) and all(x[0] == " " for x in strings):
5935+
strings = [x[1:] for x in strings]
5936+
return strings
59395937

59405938

59415939
def _validate_join_method(method: str):
@@ -6003,15 +6001,11 @@ def _maybe_cast_with_dtype(data: np.ndarray, dtype: np.dtype, copy: bool) -> np.
60036001
except ValueError:
60046002
data = np.array(data, dtype=np.float64, copy=copy)
60056003

6006-
elif inferred == "string":
6007-
pass
6008-
else:
6004+
elif inferred != "string":
60096005
data = data.astype(dtype)
60106006
elif is_float_dtype(dtype):
60116007
inferred = lib.infer_dtype(data, skipna=False)
6012-
if inferred == "string":
6013-
pass
6014-
else:
6008+
if inferred != "string":
60156009
data = data.astype(dtype)
60166010
else:
60176011
data = np.array(data, dtype=dtype, copy=copy)

pandas/core/indexes/datetimes.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -408,10 +408,7 @@ def _maybe_utc_convert(self, other: Index) -> Tuple["DatetimeIndex", Index]:
408408
this = self
409409

410410
if isinstance(other, DatetimeIndex):
411-
if self.tz is not None:
412-
if other.tz is None:
413-
raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex")
414-
elif other.tz is not None:
411+
if (self.tz is None) ^ (other.tz is None):
415412
raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex")
416413

417414
if not timezones.tz_compare(self.tz, other.tz):
@@ -745,8 +742,7 @@ def _get_string_slice(self, key: str):
745742
freq = getattr(self, "freqstr", getattr(self, "inferred_freq", None))
746743
parsed, reso = parsing.parse_time_string(key, freq)
747744
reso = Resolution.from_attrname(reso)
748-
loc = self._partial_date_slice(reso, parsed)
749-
return loc
745+
return self._partial_date_slice(reso, parsed)
750746

751747
def slice_indexer(self, start=None, end=None, step=None, kind=None):
752748
"""

0 commit comments

Comments
 (0)