python - pandas 将多个 groupby 结果放入同一个表中

标签 python pandas dataframe pandas-groupby

我有以下df,

ccode    year_month    user    tcode
10       201903        WF      MI
10       201903        WF      MI
10       201903        QQ      MI
10       201903        QQ      MI 
20       201904        BATCH   MI
20       201904        WF      MI
20       201904        BATCH   MI

我喜欢做以下事情,

inv_tran_user_ccode_ym_gr_df = df.groupby(
        ['tcode', 'user', 'ccode', 'year_month']).size().reset_index(name='count')

    inv_tran_user_ccode_ym_gr_df['bus_unit_pct'] = inv_tran_user_ccode_ym_gr_df['count'].div(
        inv_tran_user_ccode_ym_gr_df.groupby(['ccode', 'year_month'])['count'].transform('sum')).mul(
        100).round(2)

    inv_tran_user_ym_gr_df = df.groupby(
        ['tcode', 'user', 'year_month']).size().reset_index(name='count')

    inv_tran_user_ym_gr_df['org_pct'] = inv_tran_user_ym_gr_df['count'].div(
        inv_tran_user_ym_gr_df.groupby(['year_month'])['count'].transform('sum')).mul(
        100).round(2)

我想知道是否可以将 org_pctbus_unit_pct 放入同一个表中。

ccode    year_month    user    tcode    org_pct    bus_unit_pct
10       201903        WF      MI       50%        50%
10       201903        QQ      MI       50%        50%
20       201904        WF      MI       33%        33%
20       201904        BATCH   MI       67%        67%

最佳答案

您已经完成了所有艰苦的工作。这是一个相对简单的 merge 从这里开始:

(inv_tran_user_ccode_ym_gr_df.drop('count', axis=1)
                            .merge(inv_tran_user_ym_gr_df.drop('count', axis=1),
                                   on=['year_month', 'user', 'tcode']))

导致

  tcode   user  ccode  year_month  bus_unit_pct  org_pct
0    MI  BATCH     20      201904         66.67    66.67
1    MI     QQ     10      201903         50.00    50.00
2    MI     WF     10      201903         50.00    50.00
3    MI     WF     20      201904         33.33    33.33

关于python - pandas 将多个 groupby 结果放入同一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57077138/

相关文章:

Python:Pandas read_excel 无法打开 .xls 文件,不支持 xlrd

python - 选择 Pandas 数据数组中的特定行和列

python - 导入每个值包含列标签的数据

python - 云功能需要shebang吗?

python - 将 session ID 添加到我的 Bokeh 应用程序确实会返回空白页面

python - Azure VM 似乎会终止长时间运行的 MySql 查询

python - 如何插入部分 Pandas 数据框

python - 使 VS Code 终端匹配 Mac 上的调试环境

python - Pandas SQLalchemy : complex filter on database columns

python - 匹配两个数据帧的值并返回一个字典