Skip to content

ENH/TST: Add TestBaseArithmeticOps tests for ArrowExtensionArray #47601 #47645

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 26 commits into from
Jul 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
3deef7c
start adding arith tests
mroeschke Jul 7, 2022
82d7734
Add more arithmetic tests
mroeschke Jul 8, 2022
4957475
Override _combine in the future
mroeschke Jul 8, 2022
d976797
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 8, 2022
5c7d4bf
Finalize tests
mroeschke Jul 8, 2022
f38bf94
Add checked
mroeschke Jul 8, 2022
5b97245
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 8, 2022
6f5b57b
Can raise NotImplimented instead of TypeError now
mroeschke Jul 9, 2022
eb99dd5
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 9, 2022
d1cb7f3
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 10, 2022
3d5d96d
Fix typing, compute kernel compat
mroeschke Jul 10, 2022
f03f774
pyarrow 8 supports some duration ops
mroeschke Jul 10, 2022
726c6b7
Add to pandas compat
mroeschke Jul 10, 2022
2de348c
xor not implememnted in min pyarrow
mroeschke Jul 10, 2022
1dd2f79
xor not implememnted in min pyarrow
mroeschke Jul 10, 2022
83011d5
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 10, 2022
0aed029
Fix pyarrow=8 temporal condition
mroeschke Jul 10, 2022
d30877f
min version compat
mroeschke Jul 10, 2022
afe9468
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 11, 2022
f374451
more compat
mroeschke Jul 11, 2022
88449db
Add support for truediv
mroeschke Jul 11, 2022
4034a1c
Add floordiv
mroeschke Jul 11, 2022
9bfd503
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 12, 2022
81c609f
min version compat
mroeschke Jul 12, 2022
6bacdba
Merge remote-tracking branch 'upstream/main' into arrow/comparisons
mroeschke Jul 13, 2022
72e8923
Add comparison tests
mroeschke Jul 14, 2022
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: 2 additions & 0 deletions pandas/compat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
pa_version_under5p0,
pa_version_under6p0,
pa_version_under7p0,
pa_version_under8p0,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -158,4 +159,5 @@ def get_lzma_file() -> type[lzma.LZMAFile]:
"pa_version_under5p0",
"pa_version_under6p0",
"pa_version_under7p0",
"pa_version_under8p0",
]
93 changes: 93 additions & 0 deletions pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,76 @@
"ge": pc.greater_equal,
}

ARROW_LOGICAL_FUNCS = {
"and": NotImplemented if pa_version_under2p0 else pc.and_kleene,
"rand": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.and_kleene(y, x),
"or": NotImplemented if pa_version_under2p0 else pc.or_kleene,
"ror": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.or_kleene(y, x),
"xor": NotImplemented if pa_version_under2p0 else pc.xor,
"rxor": NotImplemented if pa_version_under2p0 else lambda x, y: pc.xor(y, x),
}

def cast_for_truediv(
arrow_array: pa.ChunkedArray, pa_object: pa.Array | pa.Scalar
) -> pa.ChunkedArray:
# Ensure int / int -> float mirroring Python/Numpy behavior
# as pc.divide_checked(int, int) -> int
if pa.types.is_integer(arrow_array.type) and pa.types.is_integer(
pa_object.type
):
return arrow_array.cast(pa.float64())
return arrow_array

def floordiv_compat(
left: pa.ChunkedArray | pa.Array | pa.Scalar,
right: pa.ChunkedArray | pa.Array | pa.Scalar,
) -> pa.ChunkedArray:
# Ensure int // int -> int mirroring Python/Numpy behavior
# as pc.floor(pc.divide_checked(int, int)) -> float
result = pc.floor(pc.divide_checked(left, right))
if pa.types.is_integer(left.type) and pa.types.is_integer(right.type):
result = result.cast(left.type)
return result

ARROW_ARITHMETIC_FUNCS = {
"add": NotImplemented if pa_version_under2p0 else pc.add_checked,
"radd": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.add_checked(y, x),
"sub": NotImplemented if pa_version_under2p0 else pc.subtract_checked,
"rsub": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.subtract_checked(y, x),
"mul": NotImplemented if pa_version_under2p0 else pc.multiply_checked,
"rmul": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.multiply_checked(y, x),
"truediv": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.divide_checked(cast_for_truediv(x, y), y),
"rtruediv": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.divide_checked(y, cast_for_truediv(x, y)),
"floordiv": NotImplemented
if pa_version_under2p0
else lambda x, y: floordiv_compat(x, y),
"rfloordiv": NotImplemented
if pa_version_under2p0
else lambda x, y: floordiv_compat(y, x),
"mod": NotImplemented,
"rmod": NotImplemented,
"divmod": NotImplemented,
"rdivmod": NotImplemented,
"pow": NotImplemented if pa_version_under2p0 else pc.power_checked,
Copy link
Member

Choose a reason for hiding this comment

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

failing with pyarrow 2.0.0

ImportError while loading conftest '/home/simon/pandas/pandas/conftest.py'.
pandas/__init__.py:48: in <module>
    from pandas.core.api import (
pandas/core/api.py:27: in <module>
    from pandas.core.arrays import Categorical
pandas/core/arrays/__init__.py:20: in <module>
    from pandas.core.arrays.string_arrow import ArrowStringArray
pandas/core/arrays/string_arrow.py:37: in <module>
    from pandas.core.arrays.arrow import ArrowExtensionArray
pandas/core/arrays/arrow/__init__.py:1: in <module>
    from pandas.core.arrays.arrow.array import ArrowExtensionArray
pandas/core/arrays/arrow/array.py:124: in <module>
    "pow": NotImplemented if pa_version_under2p0 else pc.power_checked,
E   AttributeError: module 'pyarrow.compute' has no attribute 'power_checked'

Copy link
Member

Choose a reason for hiding this comment

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

I merged @mroeschke's follow up PR (#47752), but I am now wondering: we don't have CI builds with pyarrow 2.0 to catch this?

Copy link
Member Author

Choose a reason for hiding this comment

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

We don't, only testing 1.01 (min), 5, 6, 7. IIRC pyarrow version 2 or 3 were causing the CI to time out around the read_csv tests so that's why 2 or 3 weren't included #43650

"rpow": NotImplemented
if pa_version_under2p0
else lambda x, y: pc.power_checked(y, x),
}

if TYPE_CHECKING:
from pandas import Series

Expand All @@ -74,6 +144,7 @@ def to_pyarrow_type(
elif isinstance(dtype, pa.DataType):
pa_dtype = dtype
elif dtype:
# Accepts python types too
pa_dtype = pa.from_numpy_dtype(dtype)
else:
pa_dtype = None
Expand Down Expand Up @@ -263,6 +334,28 @@ def _cmp_method(self, other, op):
result = result.to_numpy()
return BooleanArray._from_sequence(result)

def _evaluate_op_method(self, other, op, arrow_funcs):
pc_func = arrow_funcs[op.__name__]
if pc_func is NotImplemented:
raise NotImplementedError(f"{op.__name__} not implemented.")
if isinstance(other, ArrowExtensionArray):
result = pc_func(self._data, other._data)
elif isinstance(other, (np.ndarray, list)):
result = pc_func(self._data, pa.array(other, from_pandas=True))
elif is_scalar(other):
result = pc_func(self._data, pa.scalar(other))
else:
raise NotImplementedError(
f"{op.__name__} not implemented for {type(other)}"
)
return type(self)(result)

def _logical_method(self, other, op):
return self._evaluate_op_method(other, op, ARROW_LOGICAL_FUNCS)

def _arith_method(self, other, op):
return self._evaluate_op_method(other, op, ARROW_ARITHMETIC_FUNCS)

def equals(self, other) -> bool:
if not isinstance(other, ArrowExtensionArray):
return False
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/strings/object_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ def _str_get_dummies(self, sep="|"):
arr = Series(self).fillna("")
try:
arr = sep + arr + sep
except TypeError:
except (TypeError, NotImplementedError):
arr = sep + arr.astype(str) + sep

tags: set[str] = set()
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/arrays/string_/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def test_add(dtype, request):
"unsupported operand type(s) for +: 'ArrowStringArray' and "
"'ArrowStringArray'"
)
mark = pytest.mark.xfail(raises=TypeError, reason=reason)
mark = pytest.mark.xfail(raises=NotImplementedError, reason=reason)
Copy link
Member

Choose a reason for hiding this comment

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

BTW (not necessarily for this PR), but + for strings is actually implemented in Arrow, but under the "join" name (like str.join), so this could be emulated using pc.binary_join_element_wise(left, right, "") (the last empty string is to not use a separator)

request.node.add_marker(mark)

a = pd.Series(["a", "b", "c", None, None], dtype=dtype)
Expand Down Expand Up @@ -142,7 +142,7 @@ def test_add_2d(dtype, request):
def test_add_sequence(dtype, request):
if dtype.storage == "pyarrow":
reason = "unsupported operand type(s) for +: 'ArrowStringArray' and 'list'"
mark = pytest.mark.xfail(raises=TypeError, reason=reason)
mark = pytest.mark.xfail(raises=NotImplementedError, reason=reason)
request.node.add_marker(mark)

a = pd.array(["a", "b", None, None], dtype=dtype)
Expand All @@ -160,7 +160,7 @@ def test_add_sequence(dtype, request):
def test_mul(dtype, request):
if dtype.storage == "pyarrow":
reason = "unsupported operand type(s) for *: 'ArrowStringArray' and 'int'"
mark = pytest.mark.xfail(raises=TypeError, reason=reason)
mark = pytest.mark.xfail(raises=NotImplementedError, reason=reason)
request.node.add_marker(mark)

a = pd.array(["a", "b", None], dtype=dtype)
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/extension/base/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ class BaseArithmeticOpsTests(BaseOpsUtil):
* divmod_exc = TypeError
"""

series_scalar_exc: type[TypeError] | None = TypeError
frame_scalar_exc: type[TypeError] | None = TypeError
series_array_exc: type[TypeError] | None = TypeError
divmod_exc: type[TypeError] | None = TypeError
series_scalar_exc: type[Exception] | None = TypeError
frame_scalar_exc: type[Exception] | None = TypeError
series_array_exc: type[Exception] | None = TypeError
divmod_exc: type[Exception] | None = TypeError

def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
# series & scalar
Expand Down
Loading