Skip to content

[ArrowStringArray] PERF: use pyarrow.compute.utf8_length if available #41248

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 1 commit into from
May 4, 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
9 changes: 9 additions & 0 deletions pandas/core/arrays/string_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays.base import ExtensionArray
from pandas.core.arrays.boolean import BooleanDtype
from pandas.core.arrays.integer import Int64Dtype
from pandas.core.indexers import (
check_array_indexer,
validate_indices,
Expand Down Expand Up @@ -858,6 +859,14 @@ def _str_isupper(self):
else:
return super()._str_isupper()

def _str_len(self):
# utf8_length added in pyarrow 4.0.0
Copy link
Contributor

Choose a reason for hiding this comment

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

we should do this as a more general check i think (e.g. maybe defined a pyarrow_gt_400 or similar to what we do elsewhere rather than rely on checks like this (e.g. create a pyarrow.compat or similar). but let's create an issue and do a followup.

Copy link
Member Author

Choose a reason for hiding this comment

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

sgtm

if hasattr(pc, "utf8_length"):
result = pc.utf8_length(self._data)
return Int64Dtype().__from_arrow__(result)
else:
return super()._str_len()

def _str_lower(self):
return type(self)(pc.utf8_lower(self._data))

Expand Down
16 changes: 10 additions & 6 deletions pandas/tests/strings/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
MultiIndex,
Series,
isna,
notna,
)
import pandas._testing as tm

Expand Down Expand Up @@ -402,14 +401,19 @@ def test_join():
tm.assert_almost_equal(rs, xp)


def test_len():
values = Series(["foo", "fooo", "fooooo", np.nan, "fooooooo"])
def test_len(any_string_dtype):
values = Series(
["foo", "fooo", "fooooo", np.nan, "fooooooo", "foo\n", "あ"],
dtype=any_string_dtype,
)

result = values.str.len()
exp = values.map(lambda x: len(x) if notna(x) else np.nan)
tm.assert_series_equal(result, exp)
expected_dtype = "float64" if any_string_dtype == "object" else "Int64"
expected = Series([3, 4, 6, np.nan, 8, 4, 1], dtype=expected_dtype)
tm.assert_series_equal(result, expected)

# mixed

def test_len_mixed():
mixed = Series(
[
"a_b",
Expand Down