[英]Can the following transformation be done in python?
pandas 的groupby function 是你的朋友。 您可以使用它按月份和公司分组,然后重新排列以按公司(显示为索引)分组到列中:
df.groupby(['Month', 'Company'])['Sales'].sum().unstack()
在groupby(['Month', 'Company'])['Sales'].sum()
之后,您将公司作为索引,因此使用unstack()
将它们更改为列。
您可以使用DataFrame.pivot
pivot
调用将重塑 dataframe 从行到列, fillna(0)
将用零替换空单元格,最后reset_index
将摆脱分层列
df.pivot(index='Month', columns='Company', values='Sales').fillna(0).reset_index()
OUTPUT :
Company Month Apple HP
0 1 8.0 0.0
1 2 8.0 0.0
2 3 14.0 0.0
3 4 3.0 0.0
4 5 4.0 10.0
5 6 3.0 9.0
6 7 14.0 9.0
7 8 0.0 10.0
8 9 0.0 3.0
9 10 0.0 4.0
PS :建议在提问时将数据添加为文本,我们不能从图像中复制内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.