[英]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.