我有以下 df
df = pd.DataFrame({'Cat':['tq','tb','ta','tb','ta','tq','tb','tq','ta'],
'col1':['a','a','a','b','b','c','c','c','a'],
'col2':['aa','aa','aa','aa','ba','ba','cc','cc','cc'],
'val':np.random.rand(9)})
我想創建以下排名:
df['Cat'] = pd.Categorical(df['Cat'],['tb','tq','ta'])
但是,當我嘗試按總和進行分組時:
df2 = df.groupby(['col1','Cat','col2'])['val'].sum()
我最終得到了一個 27 行的表,而不是在我省略分類排名的地方會出現所需的 8 行。
我知道 27 是['col1','Cat','col2']. 我想知道如何通過而不是過濾掉組中的這些排列val != 0
uj5u.com熱心網友回復:
您可以使用中的observed引數groupby
df2 = df.groupby(['col1','Cat','col2'], observed=True)['val'].sum()
df2
# col1 Cat col2
# a tq aa 0.422378
# tb aa 0.395679
# ta aa 0.407851
# cc 0.998086
# b tb aa 0.318188
# ta ba 0.861469
# c tq ba 0.333660
# cc 0.427609
# tb cc 0.415207
# Name: val, dtype: float64
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/363099.html
