Skip to content

BUG: inconsistent name-retention in Series ops #36760

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
Oct 7, 2020
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ Numeric
- Bug in :class:`Series` where two :class:`Series` each have a :class:`DatetimeIndex` with different timezones having those indexes incorrectly changed when performing arithmetic operations (:issue:`33671`)
- Bug in :meth:`pd._testing.assert_almost_equal` was incorrect for complex numeric types (:issue:`28235`)
- Bug in :meth:`DataFrame.__rmatmul__` error handling reporting transposed shapes (:issue:`21581`)
- Bug in :class:`Series` flex arithmetic methods where the result when operating with a ``list``, ``tuple`` or ``np.ndarray`` would have an incorrect name (:issue:`36760`)
- Bug in :class:`IntegerArray` multiplication with ``timedelta`` and ``np.timedelta64`` objects (:issue:`36870`)

Conversion
Expand Down
37 changes: 37 additions & 0 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,43 @@ def all_arithmetic_operators(request):
return request.param


@pytest.fixture(
params=[
operator.add,
ops.radd,
operator.sub,
ops.rsub,
operator.mul,
ops.rmul,
operator.truediv,
ops.rtruediv,
operator.floordiv,
ops.rfloordiv,
operator.mod,
ops.rmod,
operator.pow,
ops.rpow,
operator.eq,
operator.ne,
operator.lt,
operator.le,
operator.gt,
operator.ge,
operator.and_,
ops.rand_,
operator.xor,
ops.rxor,
operator.or_,
ops.ror_,
]
)
def all_binary_operators(request):
"""
Fixture for operator and roperator arithmetic, comparison, and logical ops.
"""
return request.param


@pytest.fixture(
params=[
operator.add,
Expand Down
11 changes: 7 additions & 4 deletions pandas/core/ops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,8 @@ def arith_method_SERIES(cls, op, special):

@unpack_zerodim_and_defer(op_name)
def wrapper(left, right):

left, right = _align_method_SERIES(left, right)
res_name = get_op_result_name(left, right)
left, right = _align_method_SERIES(left, right)

lvalues = extract_array(left, extract_numpy=True)
rvalues = extract_array(right, extract_numpy=True)
Expand Down Expand Up @@ -361,8 +360,8 @@ def bool_method_SERIES(cls, op, special):

@unpack_zerodim_and_defer(op_name)
def wrapper(self, other):
self, other = _align_method_SERIES(self, other, align_asobject=True)
res_name = get_op_result_name(self, other)
self, other = _align_method_SERIES(self, other, align_asobject=True)

lvalues = extract_array(self, extract_numpy=True)
rvalues = extract_array(other, extract_numpy=True)
Expand All @@ -385,13 +384,17 @@ def flex_wrapper(self, other, level=None, fill_value=None, axis=0):
if axis is not None:
self._get_axis_number(axis)

res_name = get_op_result_name(self, other)

if isinstance(other, ABCSeries):
return self._binop(other, op, level=level, fill_value=fill_value)
elif isinstance(other, (np.ndarray, list, tuple)):
if len(other) != len(self):
raise ValueError("Lengths must be equal")
other = self._constructor(other, self.index)
return self._binop(other, op, level=level, fill_value=fill_value)
result = self._binop(other, op, level=level, fill_value=fill_value)
result.name = res_name
return result
else:
if fill_value is not None:
self = self.fillna(fill_value)
Expand Down
42 changes: 42 additions & 0 deletions pandas/tests/series/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,3 +699,45 @@ def test_datetime_understood(self):
result = series - offset
expected = pd.Series(pd.to_datetime(["2011-12-26", "2011-12-27", "2011-12-28"]))
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize(
"names",
[
("foo", None, None),
("Egon", "Venkman", None),
("NCC1701D", "NCC1701D", "NCC1701D"),
],
)
@pytest.mark.parametrize("box", [list, tuple, np.array, pd.Index, pd.Series, pd.array])
@pytest.mark.parametrize("flex", [True, False])
def test_series_ops_name_retention(flex, box, names, all_binary_operators):
# GH#33930 consistent name renteiton
op = all_binary_operators

if op is ops.rfloordiv and box in [list, tuple]:
pytest.xfail("op fails because of inconsistent ndarray-wrapping GH#28759")

left = pd.Series(range(10), name=names[0])
right = pd.Series(range(10), name=names[1])

right = box(right)
if flex:
name = op.__name__.strip("_")
if name in ["and", "rand", "xor", "rxor", "or", "ror"]:
# Series doesn't have these as flex methods
return
result = getattr(left, name)(right)
else:
result = op(left, right)

if box is pd.Index and op.__name__.strip("_") in ["rxor", "ror", "rand"]:
# Index treats these as set operators, so does not defer
assert isinstance(result, pd.Index)
return

assert isinstance(result, Series)
if box in [pd.Index, pd.Series]:
assert result.name == names[2]
else:
assert result.name == names[0]