Skip to content

PERF: improve StringArray.isna #57733

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
45 changes: 45 additions & 0 deletions pandas/_libs/missing.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,51 @@ cpdef ndarray[uint8_t] isnaobj(ndarray arr):
return result.view(np.bool_)


@cython.wraparound(False)
@cython.boundscheck(False)
cpdef ndarray[uint8_t] isna_string(ndarray arr):
Copy link
Member

Choose a reason for hiding this comment

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

Can we return a const uint8_t memory view instead of an ndarray? I still think generally better to use memoryviews over the long term to stay somewhat backend agnostic

Copy link
Member Author

Choose a reason for hiding this comment

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

I think for the return value we want a numpy array? (inside the function we could use more memoryviews)
I am actually only using this function from python, so can make this a def function and remove the return type

"""
Return boolean mask denoting which elements of a 1-D array are na-like,
assuming the array only contains pd.NA or strings (guaranteed by the
StringDtype).

This is a special case version of `isnaobj` above, specialized a subset
of possible values.

Parameters
----------
arr : ndarray

Returns
-------
result : ndarray (dtype=np.bool_)
"""
cdef:
Py_ssize_t i, n = arr.size
object val
bint is_null
ndarray result = np.zeros((<object>arr).shape, dtype=np.uint8)
flatiter it = cnp.PyArray_IterNew(arr)
flatiter it2 = cnp.PyArray_IterNew(result)

for i in range(n):
# The PyArray_GETITEM and PyArray_ITER_NEXT are faster
# equivalents to `val = values[i]`
val = cnp.PyArray_GETITEM(arr, cnp.PyArray_ITER_DATA(it))
cnp.PyArray_ITER_NEXT(it)
if val is C_NA:
# Dereference pointer (set value)
(<uint8_t *>(cnp.PyArray_ITER_DATA(it2)))[0] = <uint8_t>1
Copy link
Member

Choose a reason for hiding this comment

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

You can just assign 1U - no need for the cast on the right hand side

elif not isinstance(val, str):
# this should never be reached, but for safety
# (and doesn't give much overhead)
raise ValueError(
f"Array should only contain strings or pd.NA, got {type(val)}"
)
cnp.PyArray_ITER_NEXT(it2)
return result.view(np.bool_)


def isposinf_scalar(val: object) -> bool:
return util.is_float_object(val) and val == INF

Expand Down
3 changes: 3 additions & 0 deletions pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,9 @@ def __arrow_array__(self, type=None):
values[self.isna()] = None
return pa.array(values, type=type, from_pandas=True)

def isna(self) -> np.ndarray:
return libmissing.isna_string(self._ndarray)

def _values_for_factorize(self) -> tuple[np.ndarray, None]:
arr = self._ndarray.copy()
mask = self.isna()
Expand Down