简体   繁体   English

python pandas dataframe 多索引连接

[英]python pandas dataframe multiindex concat

how can I concat two dataframes with the same multi index in the following example?在以下示例中,如何连接具有相同多索引的两个数据帧?

Dataframe1:数据框1:

EOAN
                  Close
DateTime   Stock       
2021-02-27 EOAN   8.450
2021-03-06 EOAN   8.436
2021-03-13 EOAN   8.812
2021-03-20 EOAN   8.820
2021-03-24 EOAN   9.084

Dataframe2:数据框2:

SAP
                   Close
DateTime   Stock        
2021-02-27 SAP    102.06
2021-03-06 SAP    101.78
2021-03-13 SAP    103.04
2021-03-20 SAP    103.60
2021-03-24 SAP    103.06
                       0      1

I get following result, when the code gets executed:当代码被执行时,我得到以下结果:

DateTime   Stock               
2021-02-27 EOAN      NaN  8.450
           SAP    102.06    NaN
2021-03-06 EOAN      NaN  8.436
           SAP    101.78    NaN
2021-03-13 EOAN      NaN  8.812
           SAP    103.04    NaN
2021-03-20 EOAN      NaN  8.820
           SAP    103.60    NaN
2021-03-24 EOAN      NaN  9.084
           SAP    103.06    NaN

I get the dataframe like this:我得到这样的 dataframe :

for stock in stocks:

    df = pandas.DataFrame(app.data, columns=['DateTime', 'Close'])
    df['DateTime'] = pandas.to_datetime(df['DateTime'], yearfirst=False)
    df['Stock'] = my_stock
    df = df.set_index(['DateTime', 'Stock'])
    app.data.clear()
    
    if df_all is None:
        df_all = df
    else:
        df_all = pandas.concat([df,df_all], axis = 1)

df_all.stack()
print(df_all)

What I try to get is the following result, that also works with more than two stocks:我试图得到的是以下结果,它也适用于两种以上的股票:

DateTime   Stock   Close            
2021-02-27 EOAN    8.450  
           SAP    102.06
2021-03-06 EOAN    8.436  
           SAP    101.78
2021-03-13 EOAN    8.812  
           SAP    103.04
2021-03-20 EOAN    8.820 
           SAP    103.60    
2021-03-24 EOAN    9.084  
           SAP    103.06    

Sample data:样本数据:

df1 = pd.DataFrame.from_dict({'Close': {('2021-02-27', 'EOAN'): 8.45,
('2021-03-06', 'EOAN'): 8.436,
('2021-03-13', 'EOAN'): 8.812,
('2021-03-20', 'EOAN'): 8.82,
('2021-03-24', 'EOAN'): 9.084}})

df2 = pd.DataFrame({'Close': {('2021-02-27', 'SAP'): 102.06,
('2021-03-06', 'SAP'): 101.78,
('2021-03-13', 'SAP'): 103.04,
('2021-03-20', 'SAP'): 103.6,
('2021-03-24', 'SAP'): 103.06}})

Concatenating along the index will create a MultiIndex as the union of the indices of df1 and df2 .沿着索引连接将创建一个MultiIndex作为df1df2的索引的并集。 To get the desired output you may want to use sort_index() after concatenation:要获得所需的 output 您可能需要在连接后使用sort_index()

pd.concat([df1, df2], axis=0).sort_index()

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

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