繁体   English   中英

如何在 python 中添加/合并/连接两个或多个多索引 pandas dataframe 以低于 Z78E62621F6398F14CCE

[英]How to do add/merge/concat two or more multiindex pandas dataframe in python to get below output?

这是我的第一个 Multiindex DataFrame df0

Attributes  Adj Close        Close          High
Symbols     AARON  AART      AARON  AART    AARON  AART
Date                                                
2021-12-01  111.3  512.2     111.3  512.2   114.0 519.5
2021-12-02  116.6  512.5     116.6  512.5   116.8 519.9
2021-12-03  117.2  522.3     117.2  522.3   122.5 526.0

下一个 DataFrame df1

Attributes  Adj Close     Close        High
Symbols     FINP   FLEX   FINP  FLEX   FINP  FLEX
Date                                                
2021-12-01  204.4  18.0  204.4  18.0   213.6 18.0
2021-12-02  204.5  18.7  204.5  18.7   206.3 18.9
2021-12-03  200.8  19.5  200.8  19.5   205.8 19.6   

现在我想得到最终的 dataFrame df

Attributes  Adj Close                  Close                      High
Symbols     AARON  AART  FINP   FLEX   AARON AART  FINP   FLEX    AARON  AART   FINP   FLEX
Date                                                
2021-12-01  111.3  512.2 204.4  18.0   111.3 512.2 204.4  18.0    114.0  519.5  213.6  18.0
2021-12-02  116.6  512.5 204.5  18.7   116.6 512.5 204.5  18.7    116.8  519.9  206.3  18.9
2021-12-03  117.2  522.3 200.8  19.5   117.2 522.3 200.8  19.5    122.5  526.0  205.8  19.6

Which function/method should I use to get desired output

注意:这里添加了两个数据帧的列信息

df0.columns

MultiIndex([('Adj Close',      'AARON'),
            ('Adj Close',      'AART'),
            (    'Close',      'AARON'),
            (    'Close',      'AART'),
            (     'High',      'AARON'),
            (     'High',      'AART')],
           names=['Attributes', 'Symbols'])

df1.columns

MultiIndex([('Adj Close',      'AARON'),
            ('Adj Close',      'AART'),
            (    'Close',      'AARON'),
            (    'Close',      'AART'),
            (     'High',      'AARON'),
            (     'High',      'AART')],
           names=['Attributes', 'Symbols'])

您可以简单地pd.concat它们,并使用groupbylevel=0 (按索引的第 0(1)级分组)+ first

df = pd.concat([df0, df1]).groupby(level=0).first()

Output:

>>> df
           Adj Close                      Close                       High                    
               AARON   AART   FINP  FLEX  AARON   AART   FINP  FLEX  AARON   AART   FINP  FLEX
Symbols                                                                                       
2021-12-01     111.3  512.2  204.4  18.0  111.3  512.2  204.4  18.0  114.0  519.5  213.6  18.0
2021-12-02     116.6  512.5  204.5  18.7  116.6  512.5  204.5  18.7  116.8  519.9  206.3  18.9
2021-12-03     117.2  522.3  200.8  19.5  117.2  522.3  200.8  19.5  122.5  526.0  205.8  19.6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM