簡體   English   中英

合並 2 個具有相同列標題的數據框,創建子標題

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM