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 8 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
2 changes: 2 additions & 0 deletions pandas/_libs/groupby.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,8 @@ 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] :
compensation[lab, j] = 0.
sumx[lab, j] = t

for i in range(ncounts):
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/groupby/test_libgroupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,20 @@ 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="int64")

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

tm.assert_numpy_array_equal(
actual, np.array([[np.inf, 3], [3, np.inf]], dtype="float64")
Copy link
Member

Choose a reason for hiding this comment

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

nitpick: please define the expected on a previous line

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done

)