Skip to content
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

BUG: groupby with nans always places nans last #46584

Closed
rhshadrach opened this issue Mar 31, 2022 · 0 comments · Fixed by #46601
Closed

BUG: groupby with nans always places nans last #46584

rhshadrach opened this issue Mar 31, 2022 · 0 comments · Fixed by #46601
Labels
Algos Non-arithmetic algos: value_counts, factorize, sorting, isin, clip, shift, diff Apply Apply, Aggregate, Transform Bug Groupby Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate
Milestone

Comments

@rhshadrach
Copy link
Member

Marking as milestone 1.5 because this issue was introduced by #45953. While the output of the transform op below was also incorrect prior to this PR, we are reporting this kind of op as being fixed in the whatsnew.

When specifying sort=False and dropna=False in groupby, any null groupers are moved to the end, even when sort=False:

df = pd.DataFrame({'a': [1, 3, np.nan, 1, 2], 'b': [3, 4, 5, 6, 7]})
print(df.groupby('a', sort=False, dropna=False).grouper.result_index)
print(df.groupby('a', sort=True, dropna=False).grouper.result_index)
print(df.groupby('a', sort=False, dropna=False).sum())

gives

Float64Index([1.0, 3.0, 2.0, nan], dtype='float64', name='a')
Float64Index([1.0, 2.0, 3.0, nan], dtype='float64', name='a')
     b
a     
1.0  9
3.0  4
2.0  7
NaN  5

This is because nan is always given the largest code from factorize:

print(df.groupby('a', sort=False, dropna=False).codes)
# np.nan's code is 3, even though it is the third group encountered and so should be code 2.
[array([0, 1, 3, 0, 2])]

While only a minor issue for aggregations, transform depends on the code being properly ordered.

print(df.groupby('a', sort=False, dropna=False).transform(lambda x: x))
# Should be 3, 4, 5, 6, 7
   b
0  3
1  4
2  7
3  6
4  5
@rhshadrach rhshadrach added Groupby Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate Algos Non-arithmetic algos: value_counts, factorize, sorting, isin, clip, shift, diff Apply Apply, Aggregate, Transform labels Mar 31, 2022
@rhshadrach rhshadrach added this to the 1.5 milestone Mar 31, 2022
@rhshadrach rhshadrach added the Bug label Mar 31, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Algos Non-arithmetic algos: value_counts, factorize, sorting, isin, clip, shift, diff Apply Apply, Aggregate, Transform Bug Groupby Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant