首页 > 解决方案 > 未定义的行到列,按年和月分组

问题描述

我正在尝试更改数据框中的结构数据

year  month  count  reason 
2001  1     1       a
2001  2     3       b
2001  3     4       c
2005  1     4       a
2005  1     3       c

在新的数据框应如下所示:

year  month  count  reason_a  reason_b  reason_c  
2001  1      1      1         0         0
2001  2      3      0         3         0
2001  3      4      0         0         4
2005  1      7      4         0         3

有没有人可以展示一些 Python 代码来做到这一点?先感谢您,

标签: pythondataframe

解决方案


使用

前任。

dummies = df.join(pd.get_dummies(df["reason"],prefix='reason').mul(df['count'], axis=0))
f = {'count': 'sum', 'reason_a': 'first', 'reason_b': 'first', 'reason_c': 'last'}
df1 = dummies.groupby(['year','month'],sort=False,as_index=False).agg(f)
print(df1)

输出/输出:

   year  month  count  reason_a  reason_b  reason_c
0  2001      1      1         1         0         0
1  2001      2      3         0         3         0
2  2001      3      4         0         0         4
3  2005      1      7         4         0         3

推荐阅读