[英]How to get percentage of occurrences of a column, grouped by another column? Python
[英]get the percentage of a grouped values based on another column pands python
我的 pandas_df 中有兩列。 類別和金額。 我的數據如下所示:
category amount
home 20
home 10
fashion 20
fashion 10
celebrity 30
celebrity 40
我想對類別列進行分組並獲取每個類別的總和。 我還需要知道每個類別的百分比。
預期 output: home 30 - 23% etc
我的代碼:
dict(df.groupby(['category'])['amount'].sum().sort_values(ascending=False))
Output: home 30 fashion 30 celebrity 70
我會首先創建一個“百分比”列:
df['percent'] = df['amount'] / sum(df['amount'])
然后,您可以按類別分組並得到所需的 output,四舍五入到小數點后兩位:
df.groupby(['category']).sum().round(2)
output 將是:
amount percent
category
celebrity 70 0.54
fashion 30 0.23
home 30 0.23
根據您的業務案例,將“百分比”列用於將來的計算可能很有價值,就像您正在做的那樣。 因此,將此類列作為數據集的一部分可能是合理的。
groupby、agg sum 並計算結果總和的百分比。
g=df.groupby('category').agg(Sum=('amount','sum')).reset_index()#Calculate sum
g.assign(per=(g.Sum/(g.Sum.sum())*100).astype(int))#Calc the Percentage
category Sum per
0 celebrity 70 53
1 fashion 30 23
2 home 30 23
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.