Skip to content

Commit 95ecf62

Browse files
committed
BUG: partial string indexing with scalar
Closes pandas-dev#27516
1 parent 1fa1ad9 commit 95ecf62

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/source/whatsnew/v0.25.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ Interval
8282
Indexing
8383
^^^^^^^^
8484

85-
-
85+
- Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`)
8686
-
8787
-
8888

pandas/core/indexing.py

+5
Original file line numberDiff line numberDiff line change
@@ -1704,6 +1704,11 @@ def _is_scalar_access(self, key: Tuple):
17041704
if isinstance(ax, MultiIndex):
17051705
return False
17061706

1707+
if isinstance(k, str) and ax.is_all_dates:
1708+
# partial string indexing, df.loc['2000', 'A']
1709+
# should not be considered scalar
1710+
return False
1711+
17071712
if not ax.is_unique:
17081713
return False
17091714

pandas/tests/indexes/datetimes/test_partial_slicing.py

+11
Original file line numberDiff line numberDiff line change
@@ -468,3 +468,14 @@ def test_getitem_with_datestring_with_UTC_offset(self, start, end):
468468
with pytest.raises(ValueError, match="The index must be timezone"):
469469
df = df.tz_localize(None)
470470
df[start:end]
471+
472+
def test_slice_reduce_to_series(self):
473+
# GH 27516
474+
df = pd.DataFrame(
475+
{"A": range(24)}, index=pd.date_range("2000", periods=24, freq="M")
476+
)
477+
expected = pd.Series(
478+
range(12), index=pd.date_range("2000", periods=12, freq="M"), name="A"
479+
)
480+
result = df.loc["2000", "A"]
481+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)