Skip to content

BUG: -1 to the power of pd.NA was returning -1 (#30960) #9

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
Jan 13, 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: 0 additions & 1 deletion doc/source/user_guide/missing_data.rst
Original file line number Diff line number Diff line change
Expand Up @@ -831,7 +831,6 @@ Operation Result
================ ======
``pd.NA ** 0`` 0
``1 ** pd.NA`` 1
``-1 ** pd.NA`` -1
================ ======

In equality and comparison operations, ``pd.NA`` also propagates. This deviates
Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/missing.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -417,12 +417,12 @@ class NAType(C_NAType):
if other is C_NA:
return NA
elif isinstance(other, (numbers.Number, np.bool_)):
if other == 1 or other == -1:
if other == 1:
return other
else:
return NA
elif isinstance(other, np.ndarray):
return np.where((other == 1) | (other == -1), other, NA)
return np.where(other == 1, other, NA)

return NotImplemented

Expand Down
7 changes: 4 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin as DatetimeLikeArray
from pandas.core.arrays.sparse import SparseFrameAccessor
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.groupby import generic as groupby_generic
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import Index, ensure_index, ensure_index_from_sequences
from pandas.core.indexes.datetimes import DatetimeIndex
Expand All @@ -129,6 +128,7 @@
import pandas.plotting

if TYPE_CHECKING:
from pandas.core.groupby.generic import DataFrameGroupBy
from pandas.io.formats.style import Styler

# ---------------------------------------------------------------------
Expand Down Expand Up @@ -5777,13 +5777,14 @@ def groupby(
group_keys: bool = True,
squeeze: bool = False,
observed: bool = False,
) -> "groupby_generic.DataFrameGroupBy":
) -> "DataFrameGroupBy":
from pandas.core.groupby.generic import DataFrameGroupBy

if level is None and by is None:
raise TypeError("You have to supply one of 'by' and 'level'")
axis = self._get_axis_number(axis)

return groupby_generic.DataFrameGroupBy(
return DataFrameGroupBy(
obj=self,
keys=by,
axis=axis,
Expand Down
10 changes: 7 additions & 3 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import re
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Expand Down Expand Up @@ -101,6 +102,9 @@
from pandas.io.formats.printing import pprint_thing
from pandas.tseries.frequencies import to_offset

if TYPE_CHECKING:
from pandas.core.resample import Resampler

# goal is to be able to define the docs close to function, while still being
# able to share
_shared_docs: Dict[str, str] = dict()
Expand Down Expand Up @@ -7685,7 +7689,7 @@ def resample(
base: int = 0,
on=None,
level=None,
):
) -> "Resampler":
"""
Resample time-series data.

Expand Down Expand Up @@ -7950,10 +7954,10 @@ def resample(
2000-01-04 36 90
"""

from pandas.core.resample import resample
from pandas.core.resample import get_resampler

axis = self._get_axis_number(axis)
return resample(
return get_resampler(
self,
freq=rule,
label=label,
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -1262,15 +1262,15 @@ def _constructor(self):
return TimedeltaIndexResampler


def resample(obj, kind=None, **kwds):
def get_resampler(obj, kind=None, **kwds):
"""
Create a TimeGrouper and return our resampler.
"""
tg = TimeGrouper(**kwds)
return tg._get_resampler(obj, kind=kind)


resample.__doc__ = Resampler.__doc__
get_resampler.__doc__ = Resampler.__doc__


def get_resampler_for_grouping(
Expand Down
7 changes: 4 additions & 3 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@
is_empty_data,
sanitize_array,
)
from pandas.core.groupby import generic as groupby_generic
from pandas.core.indexers import maybe_convert_indices
from pandas.core.indexes.accessors import CombinedDatetimelikeProperties
from pandas.core.indexes.api import (
Expand All @@ -94,6 +93,7 @@

if TYPE_CHECKING:
from pandas.core.frame import DataFrame
from pandas.core.groupby.generic import SeriesGroupBy

__all__ = ["Series"]

Expand Down Expand Up @@ -1634,13 +1634,14 @@ def groupby(
group_keys: bool = True,
squeeze: bool = False,
observed: bool = False,
) -> "groupby_generic.SeriesGroupBy":
) -> "SeriesGroupBy":
from pandas.core.groupby.generic import SeriesGroupBy

if level is None and by is None:
raise TypeError("You have to supply one of 'by' and 'level'")
axis = self._get_axis_number(axis)

return groupby_generic.SeriesGroupBy(
return SeriesGroupBy(
obj=self,
keys=by,
axis=axis,
Expand Down
12 changes: 7 additions & 5 deletions pandas/tests/arrays/test_integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,24 +363,26 @@ def test_divide_by_zero(self, zero, negative):
tm.assert_numpy_array_equal(result, expected)

def test_pow_scalar(self):
a = pd.array([0, 1, None, 2], dtype="Int64")
a = pd.array([-1, 0, 1, None, 2], dtype="Int64")
result = a ** 0
expected = pd.array([1, 1, 1, 1], dtype="Int64")
expected = pd.array([1, 1, 1, 1, 1], dtype="Int64")
tm.assert_extension_array_equal(result, expected)

result = a ** 1
expected = pd.array([0, 1, None, 2], dtype="Int64")
expected = pd.array([-1, 0, 1, None, 2], dtype="Int64")
tm.assert_extension_array_equal(result, expected)

result = a ** pd.NA
expected = pd.array([None, 1, None, None], dtype="Int64")
expected = pd.array([None, None, 1, None, None], dtype="Int64")
tm.assert_extension_array_equal(result, expected)

result = a ** np.nan
expected = np.array([np.nan, 1, np.nan, np.nan], dtype="float64")
expected = np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype="float64")
tm.assert_numpy_array_equal(result, expected)

# reversed
a = a[1:] # Can't raise integers to negative powers.

result = 0 ** a
expected = pd.array([1, 0, None, 0], dtype="Int64")
tm.assert_extension_array_equal(result, expected)
Expand Down
29 changes: 16 additions & 13 deletions pandas/tests/scalar/test_na_scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,19 +96,7 @@ def test_pow_special(value, asarray):


@pytest.mark.parametrize(
"value",
[
1,
1.0,
-1,
-1.0,
True,
np.bool_(True),
np.int_(1),
np.float_(1),
np.int_(-1),
np.float_(-1),
],
"value", [1, 1.0, True, np.bool_(True), np.int_(1), np.float_(1)],
)
@pytest.mark.parametrize("asarray", [True, False])
def test_rpow_special(value, asarray):
Expand All @@ -125,6 +113,21 @@ def test_rpow_special(value, asarray):
assert result == value


@pytest.mark.parametrize(
"value", [-1, -1.0, np.int_(-1), np.float_(-1)],
)
@pytest.mark.parametrize("asarray", [True, False])
def test_rpow_minus_one(value, asarray):
if asarray:
value = np.array([value])
result = value ** pd.NA

if asarray:
result = result[0]

assert pd.isna(result)


def test_unary_ops():
assert +NA is NA
assert -NA is NA
Expand Down