[英]Pivot table in Python using Pandas
I have a data frame which has data in following format:我有一个数据框,其中包含以下格式的数据:
I have to pivot up the Status column and Pivot down the states Columns to make table look like:我必须 pivot 向上状态列和 Pivot 向下状态列使表格看起来像:
I am trying to do it using pd.pivot_table but unable to get the desired results.我正在尝试使用 pd.pivot_table 来做到这一点,但无法获得所需的结果。 Here is what I am trying:这是我正在尝试的:
table = pd.pivot_table(data = covid19_df_latest, index = ['Date', 'Delhi', 'Maharashtra', 'Haryana'], values = ['Status'], aggfunc = np.max)
print(table)
I am getting error "No numeric types to aggregate", Please suggest我收到错误“没有要聚合的数字类型”,请建议
Use DataFrame.melt
with DataFrame.pivot_table
:使用DataFrame.melt
和DataFrame.pivot_table
:
df= (covid19_df_latest.melt(['Date','Status'], var_name='State')
.pivot_table(index=['Date','State'],
columns='Status',
values='value',
aggfunc='max')
.reset_index()
.rename_axis(None, axis=1))
print (df)
Date State Deceased Identified Recovered
0 14/05/20 Delhi 1200 10000 2000
1 14/05/20 Haryana 1000 20000 800
2 14/05/20 Maharashtra 1000 15000 3700
Details : Solution first unpivot Dataframe by melt
:详细信息:解决方案首先通过melt
取消 Dataframe :
print (covid19_df_latest.melt(['Date','Status'], var_name='State'))
Date Status State value
0 14/05/20 Identified Delhi 10000
1 14/05/20 Recovered Delhi 2000
2 14/05/20 Deceased Delhi 1200
3 14/05/20 Identified Maharashtra 15000
4 14/05/20 Recovered Maharashtra 3700
5 14/05/20 Deceased Maharashtra 1000
6 14/05/20 Identified Haryana 20000
7 14/05/20 Recovered Haryana 800
8 14/05/20 Deceased Haryana 1000
and then pivoting with max
aggregate function.然后使用max
聚合 function 进行旋转。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.