I'm encountering some unexpected Pandas groupby-apply results, and I can't figure out the exact cause.
Below I have to dataframes that are equal except the ordering of 2 values. df1 produces results as I expect them, but df2 produces a completely different result.
import numpy as np
df1 = pd.DataFrame({'group_col': [0.0, np.nan, 0.0, 0.0], 'value_col': [2,2,2,2]})
df2 = pd.DataFrame({'group_col': [np.nan, 0.0, 0.0, 0.0], 'value_col': [2,2,2,2]})
df1:
group_col value_col
0 0.0 2
1 NaN 2
2 0.0 2
3 0.0 2
df2:
group_col value_col
0 NaN 2
1 0.0 2
2 0.0 2
3 0.0 2
When I groupby the group_col and do a value_counts of the value_col per group, including a reindex to include all possible values in the result I get the following for df1:
df1.groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))
group_col
0.0 1 NaN
2 3.0
3 NaN
Name: value_col, dtype: float64
It correctly finds 1 group and returns a multi-index series with the value_counts for each possible value. But when I run the same on df2, I get a completely different result:
0 NaN
1 NaN
2 3.0
3 NaN
Name: value_col, dtype: float64
Here the result contains an index matching the original DataFrame instead of the multi-index I would expect. I thought it might have something to do with the group column starting with np.nan, but then I tried dropping the last row and I get the expected result again, so apparently the cause is something else.
df2.head(3).groupby('group_col').value_col.apply(lambda x: x.value_counts().reindex(index=[1,2,3]))
group_col
0.0 1 NaN
2 2.0
3 NaN
Name: value_col, dtype: float64
What could be causing this?