python - pandas 在 groupby sum 之后对每组内的值进行排序,并在使用 cumsum 后获取值的百分比

标签 python python-3.x pandas dataframe pandas-groupby

我有以下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 idyear_month并获得amountsum > 首先,

df_1 = df.groupby(['id', 'year_month'], as_index=False)['amount'].sum()

然后将amount总和除以year_monthgroupbyamount总和,

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小于或等于80id的百分比;我想知道执行此操作的最佳方法是什么,结果将如下所示(使用 year_month 值作为标题);

201903    201904
25%       50%

最佳答案

函数groupby默认按分组列排序,因此应省略sort_values。然后使用带有累积和的自定义 lambda 函数,通过 Series.le 进行比较对于 True 的百分比,使用 mean,最后将 SeriesSeries.to_frame 转换为一列 DataFrameDataFrame.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/

相关文章:

python - 获取迭代过程中变量的名称

Python Bokeh 将绘图的一部分作为链接

python - 如何将文件夹添加到给定 Anaconda 环境的搜索路径?

python-3.x - 使用定制的距离函数从 Pandas Dataframe 创建距离矩阵

python - 将行附加到空 DataFrame 不起作用

python - 按索引列表从 numpy 数组中切片子数组

python - subprocess.wait() 的返回码有多少种

python - CSS 未在 CGI 脚本中应用

python - 传递类实例化(分层)

python - 使用 to_sql 和 sqlalchemy 将 pandas 数据框转换为 mariadb 数据库