[英]Merge 2 dataframes with same column headers creating subheaders
我有 2 个数据框与 Covid-19 有关
df_infect
Dates Australia Bahamas .......
1/22/20 0 0 .......
1/23/20 0 1 .......
和
df_death
Dates Australia Bahamas .......
1/22/20 0 0 .......
1/23/20 0 0 .......
我想以 dataframe 结束,它是两者的组合,就像这样,
df_combined
Australia Bahamas ......
Dates Infected Dead Infected Dead
1/22/20 0 0 0 0
1/23/20 0 0 1 0
我假设您可以对数据帧进行一些奇特的合并,但我无法锻炼您的操作方式。
您可以使用适当的后缀合并Dates
; 然后拆分列名以创建 MultiIndex 列:
out = pd.merge(df_infect, df_death, on='Dates', suffixes=('_infected','_dead')).set_index('Dates')
out.columns = out.columns.str.split('_', expand=True)
out = out.sort_index(level=[0,1], axis=1, ascending=[True, False])
Output:
Australia Bahamas
infected dead infected dead
Dates
1/22/20 0 0 0 0
1/23/20 0 0 1 0
您可以向每个 dataframe 添加一个临时列来描述其类型,然后将它们连接起来,以及 pivot:
new_df = pd.concat([df_deaths.assign(type='Death'), df_infect.assign(type='Infected')]).pivot(index='Dates', columns='type')
Output:
>>> new_df
Australia Bahamas
type Death Infected Death Infected
Dates
1/22/20 0 0 0 0
1/23/20 0 0 0 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.