Skip to content

CLN: Simplify to_masked implementation #52920

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 2 commits into from
Apr 28, 2023
Merged
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
35 changes: 6 additions & 29 deletions pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
)
from pandas.core.strings.base import BaseStringArrayMethods

from pandas.io._util import _arrow_dtype_mapping
from pandas.tseries.frequencies import to_offset

if not pa_version_under7p0:
Expand Down Expand Up @@ -1729,42 +1730,18 @@ def _replace_with_mask(

def _to_masked(self):
pa_dtype = self._pa_array.type
na_value = 1
from pandas.core.arrays import (
BooleanArray,
FloatingArray,
IntegerArray,
)

arr_cls: type[FloatingArray | IntegerArray | BooleanArray]
if pa.types.is_floating(pa_dtype):
nbits = pa_dtype.bit_width
dtype = f"Float{nbits}"
np_dtype = dtype.lower()
arr_cls = FloatingArray
elif pa.types.is_unsigned_integer(pa_dtype):
nbits = pa_dtype.bit_width
dtype = f"UInt{nbits}"
np_dtype = dtype.lower()
arr_cls = IntegerArray

elif pa.types.is_signed_integer(pa_dtype):
nbits = pa_dtype.bit_width
dtype = f"Int{nbits}"
np_dtype = dtype.lower()
arr_cls = IntegerArray

if pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype):
na_value = 1
elif pa.types.is_boolean(pa_dtype):
dtype = "boolean"
np_dtype = "bool"
na_value = True
arr_cls = BooleanArray
else:
raise NotImplementedError

dtype = _arrow_dtype_mapping()[pa_dtype]
Copy link
Member

Choose a reason for hiding this comment

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

could we simplify even more by just doing self.dtype.numpy_dtype? Aside from that, LGTM

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'd prefer keeping the mask stuff, this should make the conversion faster

Copy link
Member

Choose a reason for hiding this comment

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

Sounds good.

mask = self.isna()
arr = self.to_numpy(dtype=np_dtype, na_value=na_value)
return arr_cls(arr, mask)
arr = self.to_numpy(dtype=dtype.numpy_dtype, na_value=na_value)
return dtype.construct_array_type()(arr, mask)

def _groupby_op(
self,
Expand Down