[英]How to divide each values of the group with total size in python?
我在“質量”、“價格”、“時間”列中有一個帶有是/否答案的數據框。
我在 1 和 0 中轉換並分組
grouped = df.group.by(['country'])[['quality','price','time']].sum()
只得到“是”的答案,結果是:
國家 | 質量 | 價格 | 時間 |
---|---|---|---|
法國 | 5 | 4 | 3 |
德國 | 3 | 2 | 6 |
英國 | 2 | 1 | 4 |
我想知道如何根據每個國家/地區受訪者的大小(總計 N)划分 groupby 中的每個值,在我的情況下為 FRANCE = 9、GERMANY = 11、UK = 12。
我知道我可以選擇單個組並使用它進行操作: france = country_split.loc[['FRANCE']]
(france/9)*100
但是可以一次對整個組進行操作嗎?
使用Series.value_counts
進行計數並在匯總sum
之后除以列的sum
,然后乘以100
:
#if need dict for counts
#s = {'FRANCE': 9, 'GERMANY': 11, 'UK': 12}
s = df['country'].value_counts()
grouped = df.groupby(['country'])[['quality','price','time']].sum().div(s, axis=0).mul(100)
print (grouped)
quality price time
country
FRANCE 55.555556 44.444444 33.333333
GERMANY 27.272727 18.181818 54.545455
UK 16.666667 8.333333 33.333333
未測試,但可能的解決方案應該是聚合mean
而不是sum
:
grouped = df.groupby(['country'])[['quality','price','time']].mean()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.