Skip to content
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

BUG: reindex not matching categoricals and new string dtypes #56106

Merged
merged 7 commits into from
Dec 9, 2023
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ Strings
^^^^^^^
- Bug in :func:`pandas.api.types.is_string_dtype` while checking object array with no elements is of the string dtype (:issue:`54661`)
- Bug in :meth:`DataFrame.apply` failing when ``engine="numba"`` and columns or index have ``StringDtype`` (:issue:`56189`)
- Bug in :meth:`DataFrame.reindex` not matching :class:`Index` with ``string[pyarrow_numpy]`` dtype (:issue:`56106`)
- Bug in :meth:`Index.str.cat` always casting result to object dtype (:issue:`56157`)
- Bug in :meth:`Series.__mul__` for :class:`ArrowDtype` with ``pyarrow.string`` dtype and ``string[pyarrow]`` for the pyarrow backend (:issue:`51970`)
- Bug in :meth:`Series.str.replace` when ``n < 0`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`56404`)
Expand Down
13 changes: 12 additions & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,10 @@
ExtensionArray,
TimedeltaArray,
)
from pandas.core.arrays.string_ import StringArray
from pandas.core.arrays.string_ import (
StringArray,
StringDtype,
)
from pandas.core.base import (
IndexOpsMixin,
PandasObject,
Expand Down Expand Up @@ -5574,6 +5577,14 @@ def equals(self, other: Any) -> bool:
# quickly return if the lengths are different
return False

if (
isinstance(self.dtype, StringDtype)
and self.dtype.storage == "pyarrow_numpy"
and other.dtype != self.dtype
):
# special case for object behavior
return other.equals(self.astype(object))

if is_object_dtype(self.dtype) and not is_object_dtype(other.dtype):
# if other is not object, use other's logic for coercion
return other.equals(self)
Expand Down
69 changes: 38 additions & 31 deletions pandas/tests/indexing/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import numpy as np
import pytest

import pandas.util._test_decorators as td

import pandas as pd
from pandas import (
Categorical,
Expand All @@ -14,6 +16,7 @@
Series,
Timedelta,
Timestamp,
option_context,
)
import pandas._testing as tm

Expand Down Expand Up @@ -428,38 +431,42 @@ def test_ix_categorical_index(self):
expect = DataFrame(df.loc[:, ["X", "Y"]], index=cdf.index, columns=exp_columns)
tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)

def test_ix_categorical_index_non_unique(self):
@pytest.mark.parametrize(
"infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]
)
def test_ix_categorical_index_non_unique(self, infer_string):
# non-unique
df = DataFrame(
np.random.default_rng(2).standard_normal((3, 3)),
index=list("ABA"),
columns=list("XYX"),
)
cdf = df.copy()
cdf.index = CategoricalIndex(df.index)
cdf.columns = CategoricalIndex(df.columns)

exp_index = CategoricalIndex(list("AA"), categories=["A", "B"])
expect = DataFrame(df.loc["A", :], columns=cdf.columns, index=exp_index)
tm.assert_frame_equal(cdf.loc["A", :], expect)

exp_columns = CategoricalIndex(list("XX"), categories=["X", "Y"])
expect = DataFrame(df.loc[:, "X"], index=cdf.index, columns=exp_columns)
tm.assert_frame_equal(cdf.loc[:, "X"], expect)

expect = DataFrame(
df.loc[["A", "B"], :],
columns=cdf.columns,
index=CategoricalIndex(list("AAB")),
)
tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect)

expect = DataFrame(
df.loc[:, ["X", "Y"]],
index=cdf.index,
columns=CategoricalIndex(list("XXY")),
)
tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)
with option_context("future.infer_string", infer_string):
df = DataFrame(
np.random.default_rng(2).standard_normal((3, 3)),
index=list("ABA"),
columns=list("XYX"),
)
cdf = df.copy()
cdf.index = CategoricalIndex(df.index)
cdf.columns = CategoricalIndex(df.columns)

exp_index = CategoricalIndex(list("AA"), categories=["A", "B"])
expect = DataFrame(df.loc["A", :], columns=cdf.columns, index=exp_index)
tm.assert_frame_equal(cdf.loc["A", :], expect)

exp_columns = CategoricalIndex(list("XX"), categories=["X", "Y"])
expect = DataFrame(df.loc[:, "X"], index=cdf.index, columns=exp_columns)
tm.assert_frame_equal(cdf.loc[:, "X"], expect)

expect = DataFrame(
df.loc[["A", "B"], :],
columns=cdf.columns,
index=CategoricalIndex(list("AAB")),
)
tm.assert_frame_equal(cdf.loc[["A", "B"], :], expect)

expect = DataFrame(
df.loc[:, ["X", "Y"]],
index=cdf.index,
columns=CategoricalIndex(list("XXY")),
)
tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)

def test_loc_slice(self, df):
# GH9748
Expand Down
Loading