BUG: groupby with nans always places nans last · Issue #46584 · pandas-dev/pandas (original) (raw)

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