Skip to content

Commit b376fb9

Browse files
Backport PR #38099: BUG: fix wrong error message in deprecated 2D indexing of Series with datetime values (#38210)
1 parent ec30ff7 commit b376fb9

File tree

3 files changed

+37
-4
lines changed

3 files changed

+37
-4
lines changed

pandas/core/internals/blocks.py

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

2298+
def _check_ndim(self, values, ndim):
2299+
"""
2300+
ndim inference and validation.
2301+
2302+
This is overriden by the DatetimeTZBlock to check the case of 2D
2303+
data (values.ndim == 2), which should only be allowed if ndim is
2304+
also 2.
2305+
The case of 1D array is still allowed with both ndim of 1 or 2, as
2306+
if the case for other EAs. Therefore, we are only checking
2307+
`values.ndim > ndim` instead of `values.ndim != ndim` as for
2308+
consolidated blocks.
2309+
"""
2310+
if ndim is None:
2311+
ndim = values.ndim
2312+
2313+
if values.ndim > ndim:
2314+
raise ValueError(
2315+
"Wrong number of dimensions. "
2316+
f"values.ndim != ndim [{values.ndim} != {ndim}]"
2317+
)
2318+
return ndim
2319+
22982320

22992321
class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock):
23002322
__slots__ = ()

pandas/core/series.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -967,7 +967,8 @@ def _get_values(self, indexer):
967967
except ValueError:
968968
# mpl compat if we look up e.g. ser[:, np.newaxis];
969969
# see tests.series.timeseries.test_mpl_compat_hack
970-
return self._values[indexer]
970+
# the asarray is needed to avoid returning a 2D DatetimeArray
971+
return np.asarray(self._values)[indexer]
971972

972973
def _get_value(self, label, takeable: bool = False):
973974
"""

pandas/tests/series/indexing/test_getitem.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,20 @@ def test_getitem_generator(string_series):
133133
tm.assert_series_equal(result2, expected)
134134

135135

136-
def test_getitem_ndim_deprecated():
137-
s = pd.Series([0, 1])
136+
@pytest.mark.parametrize(
137+
"series",
138+
[
139+
Series([0, 1]),
140+
Series(date_range("2012-01-01", periods=2)),
141+
Series(date_range("2012-01-01", periods=2, tz="CET")),
142+
],
143+
)
144+
def test_getitem_ndim_deprecated(series):
138145
with tm.assert_produces_warning(FutureWarning):
139-
s[:, None]
146+
result = series[:, None]
147+
148+
expected = np.asarray(series)[:, None]
149+
tm.assert_numpy_array_equal(result, expected)
140150

141151

142152
def test_getitem_assignment_series_aligment():

0 commit comments

Comments
 (0)