Skip to content

BUG: 1D slices over extension types turn into N-dimensional slices over ExtensionArrays #42787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Fixed regressions

Bug fixes
~~~~~~~~~
-
- 1D slices over extension types turn into N-dimensional slices over ExtensionArrays (:issue:`42430`)
-

.. ---------------------------------------------------------------------------
Expand Down
8 changes: 3 additions & 5 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1552,12 +1552,10 @@ def _slice(self, slicer):
def getitem_block_index(self, slicer: slice) -> ExtensionBlock:
"""
Perform __getitem__-like specialized to slicing along index.

Assumes self.ndim == 2
"""
# error: Invalid index type "Tuple[ellipsis, slice]" for
# "Union[ndarray, ExtensionArray]"; expected type "Union[int, slice, ndarray]"
new_values = self.values[..., slicer] # type: ignore[index]
# GH#42787 in principle this is equivalent to values[..., slicer], but we don't
# require subclasses of ExtensionArray to support that form (for now).
new_values = self.values[slicer]
return type(self)(new_values, self._mgr_locs, ndim=self.ndim)

def fillna(
Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/extension/base/getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,23 @@ def test_item(self, data):

with pytest.raises(ValueError, match=msg):
s.item()

def test_ellipsis_index(self):
# GH42430 1D slices over extension types turn into N-dimensional slices over
# ExtensionArrays
class CapturingStringArray(pd.arrays.StringArray):
"""Extend StringArray to capture arguments to __getitem__"""

def __getitem__(self, item):
self.last_item_arg = item
return super().__getitem__(item)

df = pd.DataFrame(
{"col1": CapturingStringArray(np.array(["hello", "world"], dtype=object))}
)
_ = df.iloc[:1]

# String comparison because there's no native way to compare slices.
# Before the fix for GH42430, last_item_arg would get set to the 2D slice
# (Ellipsis, slice(None, 1, None))
self.assert_equal(str(df["col1"].array.last_item_arg), "slice(None, 1, None)")