Skip to content

Commit 03771a2

Browse files
BUG: fix wrong error message in deprecated 2D indexing of Series with datetime values (#38099)
1 parent 56b9a80 commit 03771a2

File tree

3 files changed

+40
-5
lines changed

3 files changed

+40
-5
lines changed

pandas/core/internals/blocks.py

+22
Original file line numberDiff line numberDiff line change
@@ -2393,6 +2393,28 @@ def quantile(self, qs, interpolation="linear", axis=0):
23932393
aware = self._holder(res_blk.values.ravel(), dtype=self.dtype)
23942394
return self.make_block_same_class(aware, ndim=res_blk.ndim)
23952395

2396+
def _check_ndim(self, values, ndim):
2397+
"""
2398+
ndim inference and validation.
2399+
2400+
This is overriden by the DatetimeTZBlock to check the case of 2D
2401+
data (values.ndim == 2), which should only be allowed if ndim is
2402+
also 2.
2403+
The case of 1D array is still allowed with both ndim of 1 or 2, as
2404+
if the case for other EAs. Therefore, we are only checking
2405+
`values.ndim > ndim` instead of `values.ndim != ndim` as for
2406+
consolidated blocks.
2407+
"""
2408+
if ndim is None:
2409+
ndim = values.ndim
2410+
2411+
if values.ndim > ndim:
2412+
raise ValueError(
2413+
"Wrong number of dimensions. "
2414+
f"values.ndim != ndim [{values.ndim} != {ndim}]"
2415+
)
2416+
return ndim
2417+
23962418

23972419
class TimeDeltaBlock(DatetimeLikeBlockMixin):
23982420
__slots__ = ()

pandas/core/series.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -916,7 +916,8 @@ def _get_values(self, indexer):
916916
except ValueError:
917917
# mpl compat if we look up e.g. ser[:, np.newaxis];
918918
# see tests.series.timeseries.test_mpl_compat_hack
919-
return self._values[indexer]
919+
# the asarray is needed to avoid returning a 2D DatetimeArray
920+
return np.asarray(self._values[indexer])
920921

921922
def _get_value(self, label, takeable: bool = False):
922923
"""

pandas/tests/series/indexing/test_getitem.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -389,10 +389,22 @@ def test_getitem_generator(string_series):
389389
tm.assert_series_equal(result2, expected)
390390

391391

392-
def test_getitem_ndim_deprecated():
393-
s = Series([0, 1])
394-
with tm.assert_produces_warning(FutureWarning):
395-
s[:, None]
392+
@pytest.mark.parametrize(
393+
"series",
394+
[
395+
Series([0, 1]),
396+
Series(date_range("2012-01-01", periods=2)),
397+
Series(date_range("2012-01-01", periods=2, tz="CET")),
398+
],
399+
)
400+
def test_getitem_ndim_deprecated(series):
401+
with tm.assert_produces_warning(
402+
FutureWarning, match="Support for multi-dimensional indexing"
403+
):
404+
result = series[:, None]
405+
406+
expected = np.asarray(series)[:, None]
407+
tm.assert_numpy_array_equal(result, expected)
396408

397409

398410
def test_getitem_multilevel_scalar_slice_not_implemented(

0 commit comments

Comments
 (0)