Merge multi-indexed with single-indexed data frames in pandas

后端 未结 3 674
别那么骄傲
别那么骄傲 2021-01-30 17:21

I have two dataframes. df1 is multi-indexed:

                value
first second    
a     x         0.471780
      y         0.774908
      z         0.563634
b          


        
3条回答
  •  梦谈多话
    2021-01-30 18:03

    You could use get_level_values:

    firsts = df1.index.get_level_values('first')
    df1['value2'] = df2.loc[firsts].values
    

    Note: you are almost doing a join here (except the df1 is MultiIndex)... so there may be a neater way to describe this...

    .

    In an example (similar to what you have):

    df1 = pd.DataFrame([['a', 'x', 0.123], ['a','x', 0.234],
                        ['a', 'y', 0.451], ['b', 'x', 0.453]],
                       columns=['first', 'second', 'value1']
                       ).set_index(['first', 'second'])
    df2 = pd.DataFrame([['a', 10],['b', 20]],
                       columns=['first', 'value']).set_index(['first'])
    
    firsts = df1.index.get_level_values('first')
    df1['value2'] = df2.loc[firsts].values
    
    In [5]: df1
    Out[5]: 
                  value1  value2
    first second                
    a     x        0.123      10
          x        0.234      10
          y        0.451      10
    b     x        0.453      20
    

提交回复
热议问题