Skip to content

Commit eb44720

Browse files
Merge branch 'main' into periodindex-to_datetime_inconsistent_with_its_docstring
2 parents 63dabc5 + 7fe270c commit eb44720

File tree

18 files changed

+93
-62
lines changed

18 files changed

+93
-62
lines changed

doc/source/whatsnew/v2.3.0.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ Interval
118118

119119
Indexing
120120
^^^^^^^^
121-
-
121+
- Fixed bug in :meth:`Index.get_indexer` round-tripping through string dtype when ``infer_string`` is enabled (:issue:`55834`)
122122
-
123123

124124
Missing

pandas/core/indexes/base.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6556,7 +6556,16 @@ def _maybe_cast_listlike_indexer(self, target) -> Index:
65566556
"""
65576557
Analogue to maybe_cast_indexer for get_indexer instead of get_loc.
65586558
"""
6559-
return ensure_index(target)
6559+
target_index = ensure_index(target)
6560+
if (
6561+
not hasattr(target, "dtype")
6562+
and self.dtype == object
6563+
and target_index.dtype == "string"
6564+
):
6565+
# If we started with a list-like, avoid inference to string dtype if self
6566+
# is object dtype (coercing to string dtype will alter the missing values)
6567+
target_index = Index(target, dtype=self.dtype)
6568+
return target_index
65606569

65616570
@final
65626571
def _validate_indexer(

pandas/core/interchange/from_dataframe.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010
import numpy as np
1111

12+
from pandas._config import using_string_dtype
13+
1214
from pandas.compat._optional import import_optional_dependency
1315

1416
import pandas as pd
@@ -147,8 +149,6 @@ def protocol_df_chunk_to_pandas(df: DataFrameXchg) -> pd.DataFrame:
147149
-------
148150
pd.DataFrame
149151
"""
150-
# We need a dict of columns here, with each column being a NumPy array (at
151-
# least for now, deal with non-NumPy dtypes later).
152152
columns: dict[str, Any] = {}
153153
buffers = [] # hold on to buffers, keeps memory alive
154154
for name in df.column_names():
@@ -347,8 +347,12 @@ def string_column_to_ndarray(col: Column) -> tuple[np.ndarray, Any]:
347347
# Add to our list of strings
348348
str_list[i] = string
349349

350-
# Convert the string list to a NumPy array
351-
return np.asarray(str_list, dtype="object"), buffers
350+
if using_string_dtype():
351+
res = pd.Series(str_list, dtype="str")
352+
else:
353+
res = np.asarray(str_list, dtype="object") # type: ignore[assignment]
354+
355+
return res, buffers # type: ignore[return-value]
352356

353357

354358
def parse_datetime_format_str(format_str, data) -> pd.Series | np.ndarray:

pandas/core/reshape/concat.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import numpy as np
1818

1919
from pandas._libs import lib
20+
from pandas.util._decorators import set_module
2021
from pandas.util._exceptions import find_stack_level
2122

2223
from pandas.core.dtypes.common import (
@@ -149,6 +150,7 @@ def concat(
149150
) -> DataFrame | Series: ...
150151

151152

153+
@set_module("pandas")
152154
def concat(
153155
objs: Iterable[Series | DataFrame] | Mapping[HashableT, Series | DataFrame],
154156
*,

pandas/tests/api/test_api.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,7 @@ def test_set_module():
417417
assert pd.Period.__module__ == "pandas"
418418
assert pd.Timestamp.__module__ == "pandas"
419419
assert pd.Timedelta.__module__ == "pandas"
420+
assert pd.concat.__module__ == "pandas"
420421
assert pd.isna.__module__ == "pandas"
421422
assert pd.notna.__module__ == "pandas"
422423
assert pd.merge.__module__ == "pandas"

pandas/tests/base/test_conversion.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import numpy as np
22
import pytest
33

4-
from pandas._config import using_string_dtype
5-
64
from pandas.compat import HAS_PYARROW
75
from pandas.compat.numpy import np_version_gt2
86

@@ -392,9 +390,6 @@ def test_to_numpy(arr, expected, zero_copy, index_or_series_or_array):
392390
assert np.may_share_memory(result_nocopy1, result_nocopy2)
393391

394392

395-
@pytest.mark.xfail(
396-
using_string_dtype() and not HAS_PYARROW, reason="TODO(infer_string)", strict=False
397-
)
398393
@pytest.mark.parametrize("as_series", [True, False])
399394
@pytest.mark.parametrize(
400395
"arr", [np.array([1, 2, 3], dtype="int64"), np.array(["a", "b", "c"], dtype=object)]
@@ -406,13 +401,13 @@ def test_to_numpy_copy(arr, as_series, using_infer_string):
406401

407402
# no copy by default
408403
result = obj.to_numpy()
409-
if using_infer_string and arr.dtype == object:
404+
if using_infer_string and arr.dtype == object and obj.dtype.storage == "pyarrow":
410405
assert np.shares_memory(arr, result) is False
411406
else:
412407
assert np.shares_memory(arr, result) is True
413408

414409
result = obj.to_numpy(copy=False)
415-
if using_infer_string and arr.dtype == object:
410+
if using_infer_string and arr.dtype == object and obj.dtype.storage == "pyarrow":
416411
assert np.shares_memory(arr, result) is False
417412
else:
418413
assert np.shares_memory(arr, result) is True

pandas/tests/indexes/multi/test_setops.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import numpy as np
22
import pytest
33

4-
from pandas._config import using_string_dtype
5-
64
import pandas as pd
75
from pandas import (
86
CategoricalIndex,
@@ -754,13 +752,12 @@ def test_intersection_keep_ea_dtypes(val, any_numeric_ea_dtype):
754752
tm.assert_index_equal(result, expected)
755753

756754

757-
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")
758755
def test_union_with_na_when_constructing_dataframe():
759756
# GH43222
760757
series1 = Series(
761758
(1,),
762759
index=MultiIndex.from_arrays(
763-
[Series([None], dtype="string"), Series([None], dtype="string")]
760+
[Series([None], dtype="str"), Series([None], dtype="str")]
764761
),
765762
)
766763
series2 = Series((10, 20), index=MultiIndex.from_tuples(((None, None), ("a", "b"))))

pandas/tests/indexes/object/test_indexing.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,15 @@ def test_get_indexer_with_NA_values(
6262
expected = np.array([0, 1, -1], dtype=np.intp)
6363
tm.assert_numpy_array_equal(result, expected)
6464

65+
def test_get_indexer_infer_string_missing_values(self):
66+
# ensure the passed list is not cast to string but to object so that
67+
# the None value is matched in the index
68+
# https://github.com/pandas-dev/pandas/issues/55834
69+
idx = Index(["a", "b", None], dtype="object")
70+
result = idx.get_indexer([None, "x"])
71+
expected = np.array([2, -1], dtype=np.intp)
72+
tm.assert_numpy_array_equal(result, expected)
73+
6574

6675
class TestGetIndexerNonUnique:
6776
def test_get_indexer_non_unique_nas(self, nulls_fixture):

pandas/tests/indexes/test_base.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,7 @@
88
import numpy as np
99
import pytest
1010

11-
from pandas._config import using_string_dtype
12-
13-
from pandas.compat import (
14-
HAS_PYARROW,
15-
IS64,
16-
)
11+
from pandas.compat import IS64
1712
from pandas.errors import InvalidIndexError
1813
import pandas.util._test_decorators as td
1914

@@ -823,11 +818,6 @@ def test_isin(self, values, index, expected):
823818
expected = np.array(expected, dtype=bool)
824819
tm.assert_numpy_array_equal(result, expected)
825820

826-
@pytest.mark.xfail(
827-
using_string_dtype() and not HAS_PYARROW,
828-
reason="TODO(infer_string)",
829-
strict=False,
830-
)
831821
def test_isin_nan_common_object(
832822
self, nulls_fixture, nulls_fixture2, using_infer_string
833823
):

pandas/tests/interchange/test_impl.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
import numpy as np
77
import pytest
88

9-
from pandas._config import using_string_dtype
10-
119
from pandas._libs.tslibs import iNaT
1210
from pandas.compat import (
1311
is_ci_environment,
@@ -401,7 +399,6 @@ def test_interchange_from_corrected_buffer_dtypes(monkeypatch) -> None:
401399
pd.api.interchange.from_dataframe(df)
402400

403401

404-
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")
405402
def test_empty_string_column():
406403
# https://github.com/pandas-dev/pandas/issues/56703
407404
df = pd.DataFrame({"a": []}, dtype=str)
@@ -410,13 +407,12 @@ def test_empty_string_column():
410407
tm.assert_frame_equal(df, result)
411408

412409

413-
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")
414410
def test_large_string():
415411
# GH#56702
416412
pytest.importorskip("pyarrow")
417413
df = pd.DataFrame({"a": ["x"]}, dtype="large_string[pyarrow]")
418414
result = pd.api.interchange.from_dataframe(df.__dataframe__())
419-
expected = pd.DataFrame({"a": ["x"]}, dtype="object")
415+
expected = pd.DataFrame({"a": ["x"]}, dtype="str")
420416
tm.assert_frame_equal(result, expected)
421417

422418

@@ -427,7 +423,6 @@ def test_non_str_names():
427423
assert names == ["0"]
428424

429425

430-
@pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")
431426
def test_non_str_names_w_duplicates():
432427
# https://github.com/pandas-dev/pandas/issues/56701
433428
df = pd.DataFrame({"0": [1, 2, 3], 0: [4, 5, 6]})
@@ -438,7 +433,7 @@ def test_non_str_names_w_duplicates():
438433
"Expected a Series, got a DataFrame. This likely happened because you "
439434
"called __dataframe__ on a DataFrame which, after converting column "
440435
r"names to string, resulted in duplicated names: Index\(\['0', '0'\], "
441-
r"dtype='object'\). Please rename these columns before using the "
436+
r"dtype='(str|object)'\). Please rename these columns before using the "
442437
"interchange protocol."
443438
),
444439
):

0 commit comments

Comments
 (0)