Skip to content

Commit d84f9eb

Browse files
authored
BUG: Series.xs boxing datetime64 incorrectly (#31630)
1 parent f5409cb commit d84f9eb

File tree

4 files changed

+26
-9
lines changed

4 files changed

+26
-9
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ Indexing
156156
- Bug in :meth:`Series.at` and :meth:`DataFrame.at` not matching ``.loc`` behavior when looking up an integer in a :class:`Float64Index` (:issue:`31329`)
157157
- Bug in :meth:`PeriodIndex.is_monotonic` incorrectly returning ``True`` when containing leading ``NaT`` entries (:issue:`31437`)
158158
- Bug in :meth:`DatetimeIndex.get_loc` raising ``KeyError`` with converted-integer key instead of the user-passed key (:issue:`31425`)
159+
- Bug in :meth:`Series.xs` incorrectly returning ``Timestamp`` instead of ``datetime64`` in some object-dtype cases (:issue:`31630`)
159160

160161
Missing
161162
^^^^^^^

pandas/core/generic.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -3442,15 +3442,14 @@ class animal locomotion
34423442
new_index = self.index[loc]
34433443

34443444
if is_scalar(loc):
3445-
new_values = self._data.fast_xs(loc)
3445+
# In this case loc should be an integer
3446+
if self.ndim == 1:
3447+
# if we encounter an array-like and we only have 1 dim
3448+
# that means that their are list/ndarrays inside the Series!
3449+
# so just return them (GH 6394)
3450+
return self._values[loc]
34463451

3447-
# may need to box a datelike-scalar
3448-
#
3449-
# if we encounter an array-like and we only have 1 dim
3450-
# that means that their are list/ndarrays inside the Series!
3451-
# so just return them (GH 6394)
3452-
if not is_list_like(new_values) or self.ndim == 1:
3453-
return com.maybe_box_datetimelike(new_values)
3452+
new_values = self._data.fast_xs(loc)
34543453

34553454
result = self._constructor_sliced(
34563455
new_values,

pandas/core/internals/managers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1565,7 +1565,7 @@ def fast_xs(self, loc):
15651565
fast path for getting a cross-section
15661566
return a view of the data
15671567
"""
1568-
return self._block.values[loc]
1568+
raise NotImplementedError("Use series._values[loc] instead")
15691569

15701570
def concat(self, to_concat, new_axis) -> "SingleBlockManager":
15711571
"""
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import numpy as np
2+
3+
import pandas as pd
4+
5+
6+
def test_xs_datetimelike_wrapping():
7+
# GH#31630 a case where we shouldn't wrap datetime64 in Timestamp
8+
arr = pd.date_range("2016-01-01", periods=3)._data._data
9+
10+
ser = pd.Series(arr, dtype=object)
11+
for i in range(len(ser)):
12+
ser.iloc[i] = arr[i]
13+
assert ser.dtype == object
14+
assert isinstance(ser[0], np.datetime64)
15+
16+
result = ser.xs(0)
17+
assert isinstance(result, np.datetime64)

0 commit comments

Comments
 (0)