python - 未定义的行到列,按年和月分组
问题描述
我正在尝试更改数据框中的结构数据
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 代码来做到这一点?先感谢您,
解决方案
使用
DataFrame.join()
- 加入另一个 DataFrame 的列。pandas.get_dummies()
- 将分类变量转换为虚拟/指标变量。DataFrame.mul()
- 获取数据帧和其他元素的乘法(二元运算符 mul)。DataFrame.groupby()
- 使用映射器或一系列列对 DataFrame 或 Series 进行分组。DataFrameGroupBy.agg()
- 使用可调用、字符串、字典或字符串/可调用列表进行聚合。
前任。
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
推荐阅读
- sql - 物化视图不更新
- java - 如何使用JSoup从html网页的表中提取特定的行数据
- r - dplyr:基于拆分因子重复行
- docker - 如何在多个 docker 容器上运行的单端口 (8888) 上访问 Jupyter Notebook?
- excel - Microsoft Excel:如何根据不同的列选择正确的单元格?
- fabricjs - 为什么 Fabricjs 中的线条和矩形不匹配
- r - ggplot 报告连续变量是分类的;我错过了什么?
- angular - 类型 'Post[]' 不可分配给类型 'Observable
': 错误 TS2322 - google-app-maker - 在非计算数据源上保存计算记录
- spring - spring data cassandra reactive - 自定义删除方法