通过multiindex在in列中搜索值并获取另一列的值

时间:2019-08-02 13:42:44

标签: python pandas multi-index

我有一个多索引数据帧df,而我有另一个数据帧df1。我喜欢在“ {corre”的值之后,在df1中搜索“ SPX”,然后在“ {corel””列中添加值df

import pandas as pd
import numpy as np

np.arrays = [['one','one','one','two','two','two'],
             ["DJ30","SPX","Example","Example","Example","Example"]]
df = pd.DataFrame(columns=[])
df = pd.DataFrame(np.random.randn(6,2),
                  index=pd.MultiIndex.from_tuples(list(zip(*np.arrays))),
                  columns=['correl','beta'])

df['correl'] = ''
df['beta'] = ''
df


df1 = pd.DataFrame([[0.95, 0.7, "SPX"]],
                  columns=['correl', 'beta', 'index'])
df1

我希望:

               correl   whatever
one     DJ30        
        SPX     0.95    
        Example     
two 
        Example     
        Example     
        Example    

1 个答案:

答案 0 :(得分:0)

您可以mergeset_indexdf.reset_index().merge(df1, left_on='level_1', right_on='index', suffixes=('_x',''), how='left')\ .set_index(['level_0','level_1'])

                 correl  beta index
level_0 level_1                    
one     DJ30        NaN   NaN   NaN
        SPX        0.95   0.7   SPX
        Example     NaN   NaN   NaN
two     Example     NaN   NaN   NaN
        Example     NaN   NaN   NaN
        Example     NaN   NaN   NaN

输出:

{{1}}