Skip to content

Commit ef1bd69

Browse files
JustinZhengBCjreback
authored andcommitted
BUG-24408 Series.dt does not maintain own copy of index (#24426)
1 parent f86af42 commit ef1bd69

File tree

5 files changed

+39
-5
lines changed

5 files changed

+39
-5
lines changed

doc/source/whatsnew/v0.24.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1322,6 +1322,7 @@ Datetimelike
13221322
- Bug in :class:`DatetimeIndex` and :class:`TimedeltaIndex` where indexing with ``Ellipsis`` would incorrectly lose the index's ``freq`` attribute (:issue:`21282`)
13231323
- Clarified error message produced when passing an incorrect ``freq`` argument to :class:`DatetimeIndex` with ``NaT`` as the first entry in the passed data (:issue:`11587`)
13241324
- Bug in :func:`to_datetime` where ``box`` and ``utc`` arguments were ignored when passing a :class:`DataFrame` or ``dict`` of unit mappings (:issue:`23760`)
1325+
- Bug in :attr:`Series.dt` where the cache would not update properly after an in-place operation (:issue:`24408`)
13251326
- Bug in :class:`PeriodIndex` where comparisons against an array-like object with length 1 failed to raise ``ValueError`` (:issue:`23078`)
13261327

13271328
Timedelta

pandas/core/indexes/accessors.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ def __init__(self, data, orig):
2727
self._parent = data
2828
self.orig = orig
2929
self.name = getattr(data, 'name', None)
30-
self.index = getattr(data, 'index', None)
3130
self._freeze()
3231

3332
def _get_values(self):
@@ -71,8 +70,7 @@ def _delegate_property_get(self, name):
7170
result = take_1d(result, self.orig.cat.codes)
7271
index = self.orig.index
7372
else:
74-
index = self.index
75-
73+
index = self._parent.index
7674
# return the result as a Series, which is by definition a copy
7775
result = Series(result, index=index, name=self.name)
7876

@@ -98,7 +96,7 @@ def _delegate_method(self, name, *args, **kwargs):
9896
if not is_list_like(result):
9997
return result
10098

101-
result = Series(result, index=self.index, name=self.name)
99+
result = Series(result, index=self._parent.index, name=self.name)
102100

103101
# setting this object will show a SettingWithCopyWarning/Error
104102
result._is_copy = ("modifications to a method of a datetimelike "
@@ -261,7 +259,7 @@ def components(self):
261259
3 0 0 0 3 0 0 0
262260
4 0 0 0 4 0 0 0
263261
""" # noqa: E501
264-
return self._get_values().components.set_index(self.index)
262+
return self._get_values().components.set_index(self._parent.index)
265263

266264
@property
267265
def freq(self):

pandas/tests/plotting/test_series.py

+12
Original file line numberDiff line numberDiff line change
@@ -890,3 +890,15 @@ def test_misc_bindings(self, mock):
890890
assert s.plot.lag() == 2
891891
assert s.plot.autocorrelation() == 2
892892
assert s.plot.bootstrap() == 2
893+
894+
@pytest.mark.xfail
895+
def test_plot_accessor_updates_on_inplace(self):
896+
s = Series([1, 2, 3, 4])
897+
_, ax = self.plt.subplots()
898+
ax = s.plot(ax=ax)
899+
before = ax.xaxis.get_ticklocs()
900+
901+
s.drop([0, 1], inplace=True)
902+
_, ax = self.plt.subplots()
903+
after = ax.xaxis.get_ticklocs()
904+
tm.assert_numpy_array_equal(before, after)

pandas/tests/series/test_api.py

+16
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,11 @@ def test_from_array_deprecated(self):
204204
with tm.assert_produces_warning(FutureWarning):
205205
self.series_klass.from_array([1, 2, 3])
206206

207+
def test_sparse_accessor_updates_on_inplace(self):
208+
s = pd.Series([1, 1, 2, 3], dtype="Sparse[int]")
209+
s.drop([0, 1], inplace=True)
210+
assert s.sparse.density == 1.0
211+
207212

208213
class TestSeriesMisc(TestData, SharedWithSparse):
209214

@@ -447,6 +452,11 @@ def f(x):
447452
exp = Series([], dtype='float64', index=Index([], dtype='float64'))
448453
tm.assert_series_equal(result, exp)
449454

455+
def test_str_accessor_updates_on_inplace(self):
456+
s = pd.Series(list('abc'))
457+
s.drop([0], inplace=True)
458+
assert len(s.str.lower()) == 2
459+
450460
def test_str_attribute(self):
451461
# GH9068
452462
methods = ['strip', 'rstrip', 'lstrip']
@@ -535,6 +545,12 @@ def test_cat_accessor_no_new_attributes(self):
535545
match="You cannot add any new attribute"):
536546
c.cat.xlabel = "a"
537547

548+
def test_cat_accessor_updates_on_inplace(self):
549+
s = Series(list('abc')).astype('category')
550+
s.drop(0, inplace=True)
551+
s.cat.remove_unused_categories(inplace=True)
552+
assert len(s.cat.categories) == 2
553+
538554
def test_categorical_delegations(self):
539555

540556
# invalid accessor

pandas/tests/series/test_datetime_values.py

+7
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,13 @@ def test_dt_accessor_invalid(self, ser):
485485
ser.dt
486486
assert not hasattr(ser, 'dt')
487487

488+
def test_dt_accessor_updates_on_inplace(self):
489+
s = Series(pd.date_range('2018-01-01', periods=10))
490+
s[2] = None
491+
s.fillna(pd.Timestamp('2018-01-01'), inplace=True)
492+
result = s.dt.date
493+
assert result[0] == result[2]
494+
488495
def test_between(self):
489496
s = Series(bdate_range('1/1/2000', periods=20).astype(object))
490497
s[::2] = np.nan

0 commit comments

Comments
 (0)