Skip to content

String dtype: implement object-dtype based StringArray variant with NumPy semantics #58451

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
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
63a7fc5
String dtype: implement object-dtype based StringArray variant with N…
jorisvandenbossche Apr 27, 2024
0eee625
fix constructor to not convert to NA
jorisvandenbossche Apr 27, 2024
607b95e
fix typing
jorisvandenbossche Apr 27, 2024
bca157d
improve logic in str_map
jorisvandenbossche Apr 27, 2024
79eb3b4
Merge remote-tracking branch 'upstream/main' into string-dtype-object
jorisvandenbossche Jul 26, 2024
c063298
Merge remote-tracking branch 'upstream/main' into string-dtype-object
jorisvandenbossche Jul 30, 2024
ab96aa4
remove most usage of python_numpy
jorisvandenbossche Jul 30, 2024
bae8d65
update tests to avoid string[python_numpy]
jorisvandenbossche Jul 30, 2024
31f1c33
Merge remote-tracking branch 'upstream/main' into string-dtype-object
jorisvandenbossche Jul 31, 2024
cbd0820
Merge remote-tracking branch 'upstream/main' into string-dtype-object
jorisvandenbossche Aug 1, 2024
864c166
remove all python_numpy usage
jorisvandenbossche Aug 1, 2024
d3ad7b0
remove hardcoded storage
jorisvandenbossche Aug 2, 2024
028dc2c
implement any/all reductions
jorisvandenbossche Aug 2, 2024
1750bcb
Merge remote-tracking branch 'upstream/main' into string-dtype-object
jorisvandenbossche Aug 3, 2024
7f4baf7
fix typing
jorisvandenbossche Aug 3, 2024
fdf1454
Merge remote-tracking branch 'upstream/main' into string-dtype-object
jorisvandenbossche Aug 7, 2024
fe6fce6
Update pandas/core/arrays/string_.py
jorisvandenbossche Aug 7, 2024
70325d4
update todo comment
jorisvandenbossche Aug 7, 2024
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 pandas/_libs/lib.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2702,7 +2702,7 @@ def maybe_convert_objects(ndarray[object] objects,
if using_string_dtype() and is_string_array(objects, skipna=True):
from pandas.core.arrays.string_ import StringDtype

dtype = StringDtype(storage="pyarrow", na_value=np.nan)
dtype = StringDtype(na_value=np.nan)
return dtype.construct_array_type()._from_sequence(objects, dtype=dtype)

elif convert_to_nullable_dtype and is_string_array(objects, skipna=True):
Expand Down
26 changes: 24 additions & 2 deletions pandas/_testing/asserters.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,13 +578,17 @@ def raise_assert_detail(

if isinstance(left, np.ndarray):
left = pprint_thing(left)
elif isinstance(left, (CategoricalDtype, NumpyEADtype, StringDtype)):
elif isinstance(left, (CategoricalDtype, NumpyEADtype)):
left = repr(left)
elif isinstance(left, StringDtype):
left = f"StringDtype(storage={left.storage}, na_value={left.na_value})"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the NA variants, do we really even need to expose/check against the storage or can we always just check that we have a StringDtype with a pd.NA missing value marker?

The main thing I want to decouple users from is relying heavily on things like StringDtype(storage="python"), because it makes it really hard to move them away from our internals.

Taking one of the examples we talked about for a possible implementation in 3.0, if we used nanoarrow to back a StringArray without taking on a pyarrow dependency, having a bunch of scattered calls to "python" makes that much harder than it needs to be, without a ton of benefit (?)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I realize the storage= keyword is documented in PDEP-14 so not surprised to see it here; I just generally am hoping to minimize how often it appears to users in non-developmental / internal contexts

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the NA variants, do we really even need to expose/check against the storage or can we always just check that we have a StringDtype with a pd.NA missing value marker?

You mean that our asserters (assert_frame_equal et al) would consider a column with string dtype backed by pyarrow vs python as equal? (as long as the na_value is equal)

The main thing I want to decouple users from is relying heavily on things like StringDtype(storage="python"), because it makes it really hard to move them away from our internals.

Yes, I also want to ensure that our general goal is that essentially almost no user should have to be explicit about the storage (that's also one of the reasons that I do not want to include the storage in the string alias for the new-to-be-default string dtype).
But, this is about a developer tool. Currently we regard pd.StringDtype("pyarrow") == pd.StringDtype("python") as False, and so assert_frame_equal will fail for that. And in that case, for the developer UX, the assert error message should be clear.

Right now, you can get something like:

AssertionError: Attributes of DataFrame.iloc[:, 0] (column name="col1") are different

Attribute "dtype" are different
[left]:  string[pyarrow]
[right]: string[pyarrow]

which is not very helpful ...

The reason for that is because I did not bake the pd.NA vs np.nan information in the string alias / representation.

See also #59342 for an issue about this that was just opened (we should probably continue the main discussion about an informative repr there, but short term I want to include something like the above as a short-term solution until we decide on the best way forward to address the issues in #59342)

FWIW I also added this code change in #59352 (to fix up failing tests on main) but with a comment explaining the issue.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean that our asserters (assert_frame_equal et al) would consider a column with string dtype backed by pyarrow vs python as equal? (as long as the na_value is equal)

Yea exactly. I'm not sure I 100% feel that way and I see both sides to the argument, but wanted to raise it for discussion

Understood and agreed on all of your other points

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the asserters and how to treat variants of the same dtype, that is a topic we certainly have to discuss more in general as well when expanding this topic to other dtypes (PDEP 13).

Personally, I think there is indeed something to say about treating those dtypes as equal, or at least have an option to toggle how "strict" the dtype check is.


if isinstance(right, np.ndarray):
right = pprint_thing(right)
elif isinstance(right, (CategoricalDtype, NumpyEADtype, StringDtype)):
elif isinstance(right, (CategoricalDtype, NumpyEADtype)):
right = repr(right)
elif isinstance(right, StringDtype):
right = f"StringDtype(storage={right.storage}, na_value={right.na_value})"

msg += f"""
[left]: {left}
Expand Down Expand Up @@ -790,6 +794,24 @@ def assert_extension_array_equal(
left_na, right_na, obj=f"{obj} NA mask", index_values=index_values
)

# Specifically for StringArrayNumpySemantics, validate here we have a valid array
if (
isinstance(left.dtype, StringDtype)
and left.dtype.storage == "python"
and left.dtype.na_value is np.nan
):
assert np.all(
[np.isnan(val) for val in left._ndarray[left_na]] # type: ignore[attr-defined]
), "wrong missing value sentinels"
if (
isinstance(right.dtype, StringDtype)
and right.dtype.storage == "python"
and right.dtype.na_value is np.nan
):
assert np.all(
[np.isnan(val) for val in right._ndarray[right_na]] # type: ignore[attr-defined]
), "wrong missing value sentinels"

left_valid = left[~left_na].to_numpy(dtype=object)
right_valid = right[~right_na].to_numpy(dtype=object)
if check_exact:
Expand Down
2 changes: 2 additions & 0 deletions pandas/compat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
)
from pandas.compat.numpy import is_numpy_dev
from pandas.compat.pyarrow import (
HAS_PYARROW,
pa_version_under10p1,
pa_version_under11p0,
pa_version_under13p0,
Expand Down Expand Up @@ -156,6 +157,7 @@ def is_ci_environment() -> bool:
"pa_version_under14p1",
"pa_version_under16p0",
"pa_version_under17p0",
"HAS_PYARROW",
"IS64",
"ISMUSL",
"PY311",
Expand Down
2 changes: 2 additions & 0 deletions pandas/compat/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
pa_version_under15p0 = _palv < Version("15.0.0")
pa_version_under16p0 = _palv < Version("16.0.0")
pa_version_under17p0 = _palv < Version("17.0.0")
HAS_PYARROW = True
except ImportError:
pa_version_under10p1 = True
pa_version_under11p0 = True
Expand All @@ -27,3 +28,4 @@
pa_version_under15p0 = True
pa_version_under16p0 = True
pa_version_under17p0 = True
HAS_PYARROW = False
2 changes: 2 additions & 0 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1295,6 +1295,7 @@ def nullable_string_dtype(request):
@pytest.fixture(
params=[
"python",
"python_numpy",
pytest.param("pyarrow", marks=td.skip_if_no("pyarrow")),
pytest.param("pyarrow_numpy", marks=td.skip_if_no("pyarrow")),
]
Expand Down Expand Up @@ -1356,6 +1357,7 @@ def object_dtype(request):
params=[
"object",
"string[python]",
"string[python_numpy]",
pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")),
pytest.param("string[pyarrow_numpy]", marks=td.skip_if_no("pyarrow")),
]
Expand Down
Loading
Loading