Skip to content Skip to sidebar Skip to footer

Pandas Groupby Two Columns, Include All Possible Values Of Column 2 Per Group

I'm sure this is a duplicate but I cant find it. I have this data frame: import pandas as pd df = pd.DataFrame(data=[['Sweden','A',5], ['Sweden','A',10],

Solution 1:

Option 1
unstack and then stack again.

df.groupby(['Country','Class']).sum().unstack().stack(dropna=False)

               Value
Country Class       
Norway  A        NaN
        B        4.0
        C        5.0
Sweden  A       15.0
        B        NaN
        C        NaN

Option 2
Another option would be to reindex with a constructed MultiIndex.

v = df.groupby(['Country','Class']).sum()
idx = pd.MultiIndex.from_product([df.Country.unique(), df.Class.unique()])

v.reindex(idx)

          Value
Sweden A   15.0
       B    NaN
       C    NaN
Norway A    NaN
       B    4.0
       C    5.0

Post a Comment for "Pandas Groupby Two Columns, Include All Possible Values Of Column 2 Per Group"