合并具有相同列 headers 的 2 个数据帧创建子 headers

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           .......

我想得到一个像这样结合了两者的数据框,

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])

输出:

        Australia       Bahamas     
         infected dead infected dead
Dates                               
1/22/20         0    0        0    0
1/23/20         0    0        1    0

您可以向每个数据框添加一个临时列来描述其类型,然后连接它们,然后进行数据透视:

new_df = pd.concat([df_deaths.assign(type='Death'), df_infect.assign(type='Infected')]).pivot(index='Dates', columns='type')

输出:

>>> new_df
        Australia          Bahamas         
type        Death Infected   Death Infected
Dates                                      
1/22/20         0        0       0        0
1/23/20         0        0       0        1