我有以下df
,
amount id year_month
20 10 201903
20 10 201903
50 20 201903
10 20 201903
5 30 201903
5 40 201903
30 50 201904
10 60 201904
10 70 201904
5 80 201904
我想groupby
id
和year_month
并获得amount
的sum
> 首先,
df_1 = df.groupby(['id', 'year_month'], as_index=False)['amount'].sum()
然后将amount
总和除以year_month
groupby
的amount
总和,
df_1['pct']=df_1['amount'].div(df_1.groupby('year_month')['amount'].transform('sum')).mul(100).round(2)
amount id year_month pct
40 10 201903 36.36
60 20 201903 54.55
5 30 201903 4.55
5 40 201903 4.55
30 50 201904 54.55
10 60 201904 18.18
10 70 201904 18.18
5 80 201904 9.09
我想首先按降序对每个year_month
内的pct
(例如201903
)进行排序;然后计算每个year_month
内总和pct
小于或等于80
的id
的百分比;我想知道执行此操作的最佳方法是什么,结果将如下所示(使用 year_month
值作为标题);
201903 201904
25% 50%
最佳答案
函数groupby
默认按分组列排序,因此应省略sort_values
。然后使用带有累积和的自定义 lambda 函数,通过 Series.le
进行比较对于 True
的百分比,使用 mean
,最后将 Series
按 Series.to_frame
转换为一列 DataFrame
与 DataFrame.T
对于转置:
df_2 = (df_1.groupby('year_month')['pct']
.apply(lambda x: x.cumsum().le(80).mean())
.mul(100)
.to_frame(0)
.T
.astype(int))
print (df_2)
year_month 201903 201904
0 25 50
关于python - pandas 在 groupby sum 之后对每组内的值进行排序,并在使用 cumsum 后获取值的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56950504/