Pandas version checks
-
[X] I have checked that this issue has not already been reported.
-
[X] I have confirmed this bug exists on the latest version of pandas.
-
[x] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
n = 32
df = pd.DataFrame({'label': [1]*n,'bool_column': [True]*(n)})
print(df.assign(bool_column_dupe=(df.bool_column==True)).groupby("label").bool_column_dupe.sum())
Issue Description
Summing a boolean column after a groupby gives an unreasonably large and incorrect sum.
This is the result from the above code:
1 8128
Name: bool_column_dupe, dtype: int64
The issue does not occur if I instead add an astype(int)
:
print(df.assign(bool_column_dupe(df.bool_column==True).astype(int)).groupby("label").bool_column_dupe.sum())
The issue does not occur if I don't use the .assign
:
print(df.groupby("label").bool_column.sum())
The issue does not occur with n<32
.
The issue only occurs with numpy v1.24.0. It does not occur with numpy v1.23.5.
Expected Behavior
Expected to see:
1 32
Name: bool_column_dupe, dtype: int64
Installed Versions
Comment From: asishm
this might be a numpy issue
In [77]: a = np.array([True] * 32)
In [78]: b = (a == True)
In [79]: b.view('uint8')
Out[79]:
array([254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
254, 254, 254, 254, 254, 254], dtype=uint8)
In [80]: np.__version__
Out[80]: '1.24.0'
Comment From: phofl
This works on main for me, so might need tests.
We made quite a lot of changes on groupby algorithms to preserve dtypes better, so could be related to that
Comment From: asishm
I don't think this works on main
In [3]: pd.__version__, np.__version__
Out[3]: ('2.0.0.dev0+971.gca3e0c875f', '1.24.0')
In [4]: n = 32
...: df = pd.DataFrame({'label': 1, 'a': [True] * n})
...: df['b'] = df['a'] == True
...: df.groupby('label').sum()
Out[4]:
a b
label
1 32 8128
Comment From: phofl
Hm good point, did not use numpy 1.24.0 I agree that this looks like a numpy bug
Comment From: agaventa
This is now fixed in numpy 1.24.1
Comment From: Daquisu
take