我有以下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_pct 和 bus_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
