Skip to content

[ArrowStringArray] use pyarrow.compute.match_substring_regex if available #41217

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 4 commits into from
May 2, 2021
Merged
Changes from 2 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
31 changes: 24 additions & 7 deletions pandas/core/arrays/string_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
Sequence,
cast,
)
import warnings

import numpy as np

Expand Down Expand Up @@ -755,15 +756,31 @@ def _str_map(self, f, na_value=None, dtype: Dtype | None = None):
return lib.map_infer_mask(arr, f, mask.view("uint8"))

def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
if not regex and case:
result = pc.match_substring(self._data, pat)
result = BooleanDtype().__from_arrow__(result)
if not isna(na):
result[isna(result)] = bool(na)
return result
else:
if flags:
return super()._str_contains(pat, case, flags, na, regex)

if regex:
if hasattr(pc, "match_substring_regex") and case:
Copy link
Member

Choose a reason for hiding this comment

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

Maybe it would be good to add a comment like "added in pyarrow x.x", so we can more easily clean up those hasattr checks if we later raise the minimum version

Copy link
Member Author

Choose a reason for hiding this comment

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

yes. I was thinking the same to address #41219 (comment)

if re.compile(pat).groups:
warnings.warn(
"This pattern has match groups. To actually get the "
"groups, use str.extract.",
UserWarning,
stacklevel=3,
)
result = pc.match_substring_regex(self._data, pat)
else:
return super()._str_contains(pat, case, flags, na, regex)
else:
if case:
result = pc.match_substring(self._data, pat)
else:
result = pc.match_substring(pc.utf8_upper(self._data), pat.upper())
result = BooleanDtype().__from_arrow__(result)
if not isna(na):
result[isna(result)] = bool(na)
return result

def _str_startswith(self, pat, na=None):
if hasattr(pc, "match_substring_regex"):
result = pc.match_substring_regex(self._data, "^" + re.escape(pat))
Expand Down