我有一個看起來像這樣的資料框:
id name industry income
1 apple telecommunication 100
2 oil gas 100
3 samsung telecommunication 200
4 coinbase crypto 100
5 microsoft telecommunication 30
所以我想做的是找到每個行業的平均收入。它將是:電信 110、天然氣 100、加密貨幣 100。
我所做的是找到每個行業的頻率:
df.groupby(['industry']).sum().value_counts('industry')
這導致:
industry
telecommunication 3
gas 1
crypto 1
而且我還找到了每個行業的收入總和:
df.groupby(['industry']).sum()['income']
這導致
industry
telecommunication 330
gas 100
crypto 100
現在我有點困惑如何繼續......
uj5u.com熱心網友回復:
您正在尋找mean:
means = df.groupby('industry')['income'].mean()
輸出:
>>> means
industry
crypto 100.0
gas 100.0
telecommunication 110.0
Name: income, dtype: float64
>>> means['telecommunication']
110.0
uj5u.com熱心網友回復:
如果您想保留所有其他詳細資訊,請分組并轉換
df['mean']=df.groupby('industry')['income'].transform('mean')
id name industry income mean
0 1 apple telecommunication 100 110.0
1 2 oil gas 100 100.0
2 3 samsung telecommunication 200 110.0
3 4 coinbase crypto 100 100.0
4 5 microsoft telecommunication 30 110.0
如果你需要一個總結框架
df.groupby('industry')['income'].mean().to_frame('mean_income')
mean_income
industry
crypto 100.0
gas 100.0
telecommunication 110.0
uj5u.com熱心網友回復:
也許你應該使用agg來避免多次操作:
out = df.groupby('industry', sort=False).agg(size=('income', 'size'),
mean=('income', 'mean'),
sum=('income', 'sum')).reset_index()
print(out)
# Output:
industry size mean sum
0 telecommunication 3 110.0 330
1 gas 1 100.0 100
2 crypto 1 100.0 100
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/389499.html
標籤:熊猫 数据框 pandas-groupby
