Skip to content

BUG: Fix np.inf + np.nan sum issue on groupby mean #52964

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 22 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
7 changes: 7 additions & 0 deletions pandas/_libs/groupby.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,13 @@ def group_mean(
y = val - compensation[lab, j]
t = sumx[lab, j] + y
compensation[lab, j] = t - sumx[lab, j] - y
if compensation[lab, j] != compensation[lab, j]:
Copy link
Member

Choose a reason for hiding this comment

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

this is to check for nan? can you use an explicit check? If not, please add a comment about what you're doing and why

Copy link
Contributor Author

@parthi-siva parthi-siva May 3, 2023

Choose a reason for hiding this comment

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

Hi @jbrockmendel, I tried do it explicitly but it is not working. I tried to use utils.is_nan since it is no gil it is not compiling. So I just used this way to determine Nan (That's what we are doing in utils.is_nan as well.)
I will add appropriate comment in the code

# GH#50367
# If val is +/- infinity, compensation is NaN
# which would lead to results being NaN instead
# of +/-infinity. We cannot use util.is_nan
# because of no gil
compensation[lab, j] = 0.
sumx[lab, j] = t

for i in range(ncounts):
Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/groupby/test_libgroupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,23 @@ def test_cython_group_mean_not_datetimelike_but_has_NaT_values():
tm.assert_numpy_array_equal(
actual[:, 0], np.array(np.divide(np.add(data[0], data[1]), 2), dtype="float64")
)


def test_cython_group_mean_Inf_at_begining_and_end():
# GH 50367
actual = np.array([[np.nan, np.nan], [np.nan, np.nan]], dtype="float64")
counts = np.array([0, 0], dtype="int64")
data = np.array(
[[np.inf, 1.0], [1.0, 2.0], [2.0, 3.0], [3.0, 4.0], [4.0, 5.0], [5, np.inf]],
dtype="float64",
)
labels = np.array([0, 1, 0, 1, 0, 1], dtype=np.intp)

group_mean(actual, counts, data, labels, is_datetimelike=False)

expected = np.array([[np.inf, 3], [3, np.inf]], dtype="float64")

tm.assert_numpy_array_equal(
actual,
expected,
)