Skip to content

Commit c22c9b8

Browse files
jbrockmendelJulianWgs
authored andcommitted
CLN: use ensure_block_shape (pandas-dev#40792)
1 parent 1f1031d commit c22c9b8

File tree

5 files changed

+30
-16
lines changed

5 files changed

+30
-16
lines changed

pandas/core/internals/array_manager.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -479,8 +479,7 @@ def apply_with_block(self: T, f, align_keys=None, swap_axis=True, **kwargs) -> T
479479
arr = arr._data # type: ignore[attr-defined]
480480

481481
if self.ndim == 2:
482-
if isinstance(arr, np.ndarray):
483-
arr = np.atleast_2d(arr)
482+
arr = ensure_block_shape(arr, 2)
484483
block = new_block(arr, placement=slice(0, 1, 1), ndim=2)
485484
else:
486485
block = new_block(arr, placement=slice(0, len(self), 1), ndim=1)
@@ -490,6 +489,7 @@ def apply_with_block(self: T, f, align_keys=None, swap_axis=True, **kwargs) -> T
490489
applied = applied[0]
491490
arr = applied.values
492491
if self.ndim == 2 and arr.ndim == 2:
492+
# 2D for np.ndarray or DatetimeArray/TimedeltaArray
493493
assert len(arr) == 1
494494
# error: Invalid index type "Tuple[int, slice]" for
495495
# "Union[ndarray, ExtensionArray]"; expected type

pandas/core/internals/blocks.py

+13-9
Original file line numberDiff line numberDiff line change
@@ -925,15 +925,6 @@ def setitem(self, indexer, value):
925925
# current dtype cannot store value, coerce to common dtype
926926
return self.coerce_to_target_dtype(value).setitem(indexer, value)
927927

928-
if self.dtype.kind in ["m", "M"]:
929-
arr = self.values
930-
if self.ndim > 1:
931-
# Dont transpose with ndim=1 bc we would fail to invalidate
932-
# arr.freq
933-
arr = arr.T
934-
arr[indexer] = value
935-
return self
936-
937928
# value must be storable at this moment
938929
if is_extension_array_dtype(getattr(value, "dtype", None)):
939930
# We need to be careful not to allow through strings that
@@ -1697,6 +1688,19 @@ def iget(self, key):
16971688
# TODO(EA2D): this can be removed if we ever have 2D EA
16981689
return self.values.reshape(self.shape)[key]
16991690

1691+
def setitem(self, indexer, value):
1692+
if not self._can_hold_element(value):
1693+
# TODO: general case needs casting logic.
1694+
return self.astype(object).setitem(indexer, value)
1695+
1696+
values = self.values
1697+
if self.ndim > 1:
1698+
# Dont transpose with ndim=1 bc we would fail to invalidate
1699+
# arr.freq
1700+
values = values.T
1701+
values[indexer] = value
1702+
return self
1703+
17001704
def putmask(self, mask, new) -> list[Block]:
17011705
mask = extract_bool_array(mask)
17021706

pandas/core/internals/managers.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030

3131
from pandas.core.dtypes.cast import infer_dtype_from_scalar
3232
from pandas.core.dtypes.common import (
33-
ensure_int64,
33+
ensure_platform_int,
3434
is_dtype_equal,
3535
is_extension_array_dtype,
3636
is_list_like,
@@ -346,6 +346,13 @@ def unpickle_block(values, mgr_locs, ndim: int):
346346
state = state[3]["0.14.1"]
347347
self.axes = [ensure_index(ax) for ax in state["axes"]]
348348
ndim = len(self.axes)
349+
350+
for blk in state["blocks"]:
351+
vals = blk["values"]
352+
# older versions may hold e.g. DatetimeIndex instead of DTA
353+
vals = extract_array(vals, extract_numpy=True)
354+
blk["values"] = ensure_block_shape(vals, ndim=ndim)
355+
349356
self.blocks = tuple(
350357
unpickle_block(b["values"], b["mgr_locs"], ndim=ndim)
351358
for b in state["blocks"]
@@ -1975,8 +1982,7 @@ def _preprocess_slice_or_indexer(
19751982
dtype = getattr(slice_or_indexer, "dtype", None)
19761983
raise TypeError(type(slice_or_indexer), dtype)
19771984

1978-
# TODO: np.intp?
1979-
indexer = ensure_int64(slice_or_indexer)
1985+
indexer = ensure_platform_int(slice_or_indexer)
19801986
if not allow_fill:
19811987
indexer = maybe_convert_indices(indexer, length)
19821988
return "fancy", indexer, len(indexer)

pandas/tests/internals/test_internals.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@
3737
SingleBlockManager,
3838
make_block,
3939
)
40-
from pandas.core.internals.blocks import new_block
40+
from pandas.core.internals.blocks import (
41+
ensure_block_shape,
42+
new_block,
43+
)
4144

4245
# this file contains BlockManager specific tests
4346
# TODO(ArrayManager) factor out interleave_dtype tests
@@ -138,6 +141,7 @@ def create_block(typestr, placement, item_shape=None, num_offset=0, maker=new_bl
138141
tz = m.groups()[0]
139142
assert num_items == 1, "must have only 1 num items for a tz-aware"
140143
values = DatetimeIndex(np.arange(N) * 1e9, tz=tz)._data
144+
values = ensure_block_shape(values, ndim=len(shape))
141145
elif typestr in ("timedelta", "td", "m8[ns]"):
142146
values = (mat * 1).astype("m8[ns]")
143147
elif typestr in ("category",):

pandas/tests/series/methods/test_isin.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def test_isin_with_i8(self):
5959
tm.assert_series_equal(result, expected)
6060

6161
# fails on dtype conversion in the first place
62-
result = s.isin(s[0:2].values.astype("datetime64[D]"))
62+
result = s.isin(np.asarray(s[0:2].values).astype("datetime64[D]"))
6363
tm.assert_series_equal(result, expected)
6464

6565
result = s.isin([s[1]])

0 commit comments

Comments
 (0)