Skip to content

Commit a145394

Browse files
jbrockmendelluckyvs1
authored andcommitted
TYP/CLN: assorted cleanups (pandas-dev#38959)
1 parent 11b0db1 commit a145394

File tree

11 files changed

+70
-65
lines changed

11 files changed

+70
-65
lines changed

pandas/_libs/tslibs/offsets.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -3565,7 +3565,7 @@ cpdef to_offset(freq):
35653565
f"to_offset does not support tuples {freq}, pass as a string instead"
35663566
)
35673567

3568-
elif isinstance(freq, timedelta):
3568+
elif PyDelta_Check(freq):
35693569
return delta_to_tick(freq)
35703570

35713571
elif isinstance(freq, str):

pandas/conftest.py

+1-9
Original file line numberDiff line numberDiff line change
@@ -1002,14 +1002,6 @@ def tz_aware_fixture(request):
10021002
tz_aware_fixture2 = tz_aware_fixture
10031003

10041004

1005-
@pytest.fixture(scope="module")
1006-
def datetime_tz_utc():
1007-
"""
1008-
Yields the UTC timezone object from the datetime module.
1009-
"""
1010-
return timezone.utc
1011-
1012-
10131005
@pytest.fixture(params=["utc", "dateutil/UTC", utc, tzutc(), timezone.utc])
10141006
def utc_fixture(request):
10151007
"""
@@ -1189,7 +1181,7 @@ def any_nullable_int_dtype(request):
11891181

11901182

11911183
@pytest.fixture(params=tm.ALL_EA_INT_DTYPES + tm.FLOAT_EA_DTYPES)
1192-
def any_numeric_dtype(request):
1184+
def any_nullable_numeric_dtype(request):
11931185
"""
11941186
Parameterized fixture for any nullable integer dtype and
11951187
any float ea dtypes.

pandas/core/internals/blocks.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -658,7 +658,7 @@ def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
658658
values = values.astype(dtype, copy=copy)
659659

660660
else:
661-
values = astype_nansafe(values, dtype, copy=True)
661+
values = astype_nansafe(values, dtype, copy=copy)
662662

663663
return values
664664

pandas/core/internals/concat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,7 @@ def _get_empty_dtype_and_na(join_units: Sequence[JoinUnit]) -> Tuple[DtypeObj, A
419419
return np.dtype("M8[ns]"), np.datetime64("NaT", "ns")
420420
elif "timedelta" in upcast_classes:
421421
return np.dtype("m8[ns]"), np.timedelta64("NaT", "ns")
422-
else: # pragma
422+
else:
423423
try:
424424
common_dtype = np.find_common_type(upcast_classes, [])
425425
except TypeError:

pandas/core/series.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4485,7 +4485,7 @@ def replace(
44854485
method=method,
44864486
)
44874487

4488-
def _replace_single(self, to_replace, method, inplace, limit):
4488+
def _replace_single(self, to_replace, method: str, inplace: bool, limit):
44894489
"""
44904490
Replaces values in a Series using the fill method specified when no
44914491
replacement value is given in the replace method

pandas/io/pytables.py

+25-21
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@
8080
if TYPE_CHECKING:
8181
from tables import Col, File, Node
8282

83+
from pandas.core.internals import Block
84+
8385

8486
# versioning attribute
8587
_version = "0.15.2"
@@ -3860,20 +3862,17 @@ def _create_axes(
38603862
for a in new_non_index_axes:
38613863
obj = _reindex_axis(obj, a[0], a[1])
38623864

3863-
def get_blk_items(mgr, blocks):
3864-
return [mgr.items.take(blk.mgr_locs) for blk in blocks]
3865-
38663865
transposed = new_index.axis == 1
38673866

38683867
# figure out data_columns and get out blocks
38693868
data_columns = self.validate_data_columns(
38703869
data_columns, min_itemsize, new_non_index_axes
38713870
)
38723871

3873-
block_obj = self.get_object(obj, transposed)._consolidate()
3872+
frame = self.get_object(obj, transposed)._consolidate()
38743873

38753874
blocks, blk_items = self._get_blocks_and_items(
3876-
block_obj, table_exists, new_non_index_axes, self.values_axes, data_columns
3875+
frame, table_exists, new_non_index_axes, self.values_axes, data_columns
38773876
)
38783877

38793878
# add my values
@@ -3978,35 +3977,39 @@ def get_blk_items(mgr, blocks):
39783977

39793978
@staticmethod
39803979
def _get_blocks_and_items(
3981-
block_obj, table_exists, new_non_index_axes, values_axes, data_columns
3980+
frame: DataFrame,
3981+
table_exists: bool,
3982+
new_non_index_axes,
3983+
values_axes,
3984+
data_columns,
39823985
):
39833986
# Helper to clarify non-state-altering parts of _create_axes
39843987

3985-
def get_blk_items(mgr, blocks):
3986-
return [mgr.items.take(blk.mgr_locs) for blk in blocks]
3988+
def get_blk_items(mgr):
3989+
return [mgr.items.take(blk.mgr_locs) for blk in mgr.blocks]
39873990

3988-
blocks = block_obj._mgr.blocks
3989-
blk_items = get_blk_items(block_obj._mgr, blocks)
3991+
blocks: List["Block"] = list(frame._mgr.blocks)
3992+
blk_items: List[Index] = get_blk_items(frame._mgr)
39903993

39913994
if len(data_columns):
39923995
axis, axis_labels = new_non_index_axes[0]
39933996
new_labels = Index(axis_labels).difference(Index(data_columns))
3994-
mgr = block_obj.reindex(new_labels, axis=axis)._mgr
3997+
mgr = frame.reindex(new_labels, axis=axis)._mgr
39953998

39963999
blocks = list(mgr.blocks)
3997-
blk_items = get_blk_items(mgr, blocks)
4000+
blk_items = get_blk_items(mgr)
39984001
for c in data_columns:
3999-
mgr = block_obj.reindex([c], axis=axis)._mgr
4002+
mgr = frame.reindex([c], axis=axis)._mgr
40004003
blocks.extend(mgr.blocks)
4001-
blk_items.extend(get_blk_items(mgr, mgr.blocks))
4004+
blk_items.extend(get_blk_items(mgr))
40024005

40034006
# reorder the blocks in the same order as the existing table if we can
40044007
if table_exists:
40054008
by_items = {
40064009
tuple(b_items.tolist()): (b, b_items)
40074010
for b, b_items in zip(blocks, blk_items)
40084011
}
4009-
new_blocks = []
4012+
new_blocks: List["Block"] = []
40104013
new_blk_items = []
40114014
for ea in values_axes:
40124015
items = tuple(ea.values)
@@ -4875,7 +4878,7 @@ def _unconvert_index(
48754878

48764879

48774880
def _maybe_convert_for_string_atom(
4878-
name: str, block, existing_col, min_itemsize, nan_rep, encoding, errors
4881+
name: str, block: "Block", existing_col, min_itemsize, nan_rep, encoding, errors
48794882
):
48804883
if not block.is_object:
48814884
return block.values
@@ -4895,11 +4898,12 @@ def _maybe_convert_for_string_atom(
48954898
elif not (inferred_type == "string" or dtype_name == "object"):
48964899
return block.values
48974900

4898-
block = block.fillna(nan_rep, downcast=False)
4899-
if isinstance(block, list):
4900-
# Note: because block is always object dtype, fillna goes
4901-
# through a path such that the result is always a 1-element list
4902-
block = block[0]
4901+
blocks: List["Block"] = block.fillna(nan_rep, downcast=False)
4902+
# Note: because block is always object dtype, fillna goes
4903+
# through a path such that the result is always a 1-element list
4904+
assert len(blocks) == 1
4905+
block = blocks[0]
4906+
49034907
data = block.values
49044908

49054909
# see if we have a valid string type

pandas/tests/indexes/datetimes/test_timezones.py

-1
Original file line numberDiff line numberDiff line change
@@ -1159,7 +1159,6 @@ def test_dti_union_mixed(self):
11591159
@pytest.mark.parametrize(
11601160
"tz", [None, "UTC", "US/Central", dateutil.tz.tzoffset(None, -28800)]
11611161
)
1162-
@pytest.mark.usefixtures("datetime_tz_utc")
11631162
def test_iteration_preserves_nanoseconds(self, tz):
11641163
# GH 19603
11651164
index = DatetimeIndex(

pandas/tests/indexes/timedeltas/test_partial_slicing.py

-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import numpy as np
2-
import pytest
32

43
from pandas import Series, timedelta_range
54
import pandas._testing as tm
@@ -22,13 +21,6 @@ def test_partial_slice(self):
2221
expected = s.iloc[:134]
2322
tm.assert_series_equal(result, expected)
2423

25-
result = s["6 days, 23:11:12"]
26-
assert result == s.iloc[133]
27-
28-
msg = r"^Timedelta\('50 days 00:00:00'\)$"
29-
with pytest.raises(KeyError, match=msg):
30-
s["50 days"]
31-
3224
def test_partial_slice_high_reso(self):
3325

3426
# higher reso

pandas/tests/series/indexing/test_getitem.py

+18
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
Timestamp,
1919
date_range,
2020
period_range,
21+
timedelta_range,
2122
)
2223
import pandas._testing as tm
2324
from pandas.core.indexing import IndexingError
@@ -121,6 +122,23 @@ def test_getitem_scalar_categorical_index(self):
121122
result = ser[cats[0]]
122123
assert result == expected
123124

125+
def test_getitem_str_with_timedeltaindex(self):
126+
rng = timedelta_range("1 day 10:11:12", freq="h", periods=500)
127+
ser = Series(np.arange(len(rng)), index=rng)
128+
129+
key = "6 days, 23:11:12"
130+
indexer = rng.get_loc(key)
131+
assert indexer == 133
132+
133+
result = ser[key]
134+
assert result == ser.iloc[133]
135+
136+
msg = r"^Timedelta\('50 days 00:00:00'\)$"
137+
with pytest.raises(KeyError, match=msg):
138+
rng.get_loc("50 days")
139+
with pytest.raises(KeyError, match=msg):
140+
ser["50 days"]
141+
124142

125143
class TestSeriesGetitemSlices:
126144
def test_getitem_partial_str_slice_with_datetimeindex(self):

pandas/tests/series/indexing/test_setitem.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -167,19 +167,19 @@ def test_setitem_boolean_td64_values_cast_na(self, value):
167167
expected = Series([NaT, 1, 2], dtype="timedelta64[ns]")
168168
tm.assert_series_equal(series, expected)
169169

170-
def test_setitem_boolean_nullable_int_types(self, any_numeric_dtype):
170+
def test_setitem_boolean_nullable_int_types(self, any_nullable_numeric_dtype):
171171
# GH: 26468
172-
ser = Series([5, 6, 7, 8], dtype=any_numeric_dtype)
173-
ser[ser > 6] = Series(range(4), dtype=any_numeric_dtype)
174-
expected = Series([5, 6, 2, 3], dtype=any_numeric_dtype)
172+
ser = Series([5, 6, 7, 8], dtype=any_nullable_numeric_dtype)
173+
ser[ser > 6] = Series(range(4), dtype=any_nullable_numeric_dtype)
174+
expected = Series([5, 6, 2, 3], dtype=any_nullable_numeric_dtype)
175175
tm.assert_series_equal(ser, expected)
176176

177-
ser = Series([5, 6, 7, 8], dtype=any_numeric_dtype)
178-
ser.loc[ser > 6] = Series(range(4), dtype=any_numeric_dtype)
177+
ser = Series([5, 6, 7, 8], dtype=any_nullable_numeric_dtype)
178+
ser.loc[ser > 6] = Series(range(4), dtype=any_nullable_numeric_dtype)
179179
tm.assert_series_equal(ser, expected)
180180

181-
ser = Series([5, 6, 7, 8], dtype=any_numeric_dtype)
182-
loc_ser = Series(range(4), dtype=any_numeric_dtype)
181+
ser = Series([5, 6, 7, 8], dtype=any_nullable_numeric_dtype)
182+
loc_ser = Series(range(4), dtype=any_nullable_numeric_dtype)
183183
ser.loc[ser > 6] = loc_ser.loc[loc_ser > 1]
184184
tm.assert_series_equal(ser, expected)
185185

pandas/tests/series/test_constructors.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -272,8 +272,8 @@ def test_constructor_index_dtype(self, dtype):
272272
[
273273
([1, 2]),
274274
(["1", "2"]),
275-
(list(pd.date_range("1/1/2011", periods=2, freq="H"))),
276-
(list(pd.date_range("1/1/2011", periods=2, freq="H", tz="US/Eastern"))),
275+
(list(date_range("1/1/2011", periods=2, freq="H"))),
276+
(list(date_range("1/1/2011", periods=2, freq="H", tz="US/Eastern"))),
277277
([Interval(left=0, right=5)]),
278278
],
279279
)
@@ -628,10 +628,10 @@ def test_constructor_copy(self):
628628
@pytest.mark.parametrize(
629629
"index",
630630
[
631-
pd.date_range("20170101", periods=3, tz="US/Eastern"),
632-
pd.date_range("20170101", periods=3),
633-
pd.timedelta_range("1 day", periods=3),
634-
pd.period_range("2012Q1", periods=3, freq="Q"),
631+
date_range("20170101", periods=3, tz="US/Eastern"),
632+
date_range("20170101", periods=3),
633+
timedelta_range("1 day", periods=3),
634+
period_range("2012Q1", periods=3, freq="Q"),
635635
Index(list("abc")),
636636
pd.Int64Index([1, 2, 3]),
637637
RangeIndex(0, 3),
@@ -1038,16 +1038,16 @@ def test_construction_consistency(self):
10381038

10391039
# make sure that we are not re-localizing upon construction
10401040
# GH 14928
1041-
s = Series(pd.date_range("20130101", periods=3, tz="US/Eastern"))
1041+
ser = Series(date_range("20130101", periods=3, tz="US/Eastern"))
10421042

1043-
result = Series(s, dtype=s.dtype)
1044-
tm.assert_series_equal(result, s)
1043+
result = Series(ser, dtype=ser.dtype)
1044+
tm.assert_series_equal(result, ser)
10451045

1046-
result = Series(s.dt.tz_convert("UTC"), dtype=s.dtype)
1047-
tm.assert_series_equal(result, s)
1046+
result = Series(ser.dt.tz_convert("UTC"), dtype=ser.dtype)
1047+
tm.assert_series_equal(result, ser)
10481048

1049-
result = Series(s.values, dtype=s.dtype)
1050-
tm.assert_series_equal(result, s)
1049+
result = Series(ser.values, dtype=ser.dtype)
1050+
tm.assert_series_equal(result, ser)
10511051

10521052
@pytest.mark.parametrize(
10531053
"data_constructor", [list, np.array], ids=["list", "ndarray[object]"]
@@ -1374,7 +1374,7 @@ def test_convert_non_ns(self):
13741374
# convert from a numpy array of non-ns timedelta64
13751375
arr = np.array([1, 2, 3], dtype="timedelta64[s]")
13761376
s = Series(arr)
1377-
expected = Series(pd.timedelta_range("00:00:01", periods=3, freq="s"))
1377+
expected = Series(timedelta_range("00:00:01", periods=3, freq="s"))
13781378
tm.assert_series_equal(s, expected)
13791379

13801380
# convert from a numpy array of non-ns datetime64

0 commit comments

Comments
 (0)