簡體   English   中英

合並兩個帶有子標題的數據框

[英]Merge two dataframes with subheaders

所以我有我的第一個數據框,其中國家作為標題,感染和死亡值作為子標題,

df
Dates       Antigua & Barbuda      Australia
          Infected      Dead      Infected   Dead
2020-01-22    0          0            0        0...
2020-01-23    0          0            0        0...
...

然后我有我的第二個數據框,

df_indicators
Dates       Location      indicator_1      indicator_2 .....
2020-04-24  Afghanistan      0                  0
2020-04-25  Afghanistan      0                  0
...
2020-04-24  Yemen            0                  0
2020-04-25  Yemen            0                  0

我想合並數據框,以便指標列成為國家列的子標題,就像在df中一樣,帶有受感染和死掉的子標題。

我想要制作的是這樣的東西,

df_merge
Dates        Antigua & Barbuda
        Infected    Dead   indicator_1   indicator_2....
2020-04-24  0         0        0             0...

有這么多指標都被命名為不同的東西,我覺得我不能把它們都叫出來,所以不確定是否有一種方法可以輕松做到這一點。

預先感謝您的任何幫助!

因為有重復項首先按mean聚合,然后通過Series.unstackDataFrame.swaplevel重塑:

df2 = df_indicators.groupby(['Dates','Location']).mean().unstack().swaplevel(0,1,axis=1)

或使用DataFrame.pivot_table

df2 = (df.pivot_table(index='Dates', columns='Location', aggfunc='mean')
         .swaplevel(0,1,axis=1))

最后加入MultiIndex in columns進行排序:

df = pd.concat([df, df2], axis=1).sort_index(axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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