How to do join of multiindex dataframe with a single index dataframe?

前端 未结 1 1535
感动是毒
感动是毒 2021-01-24 18:07

The single index of df1 matches with a sublevel of multiindex of df2. Both have the same columns. I want to copy all rows and columns of df1 to df2.

It is similar to thi

相关标签:
1条回答
  • 2021-01-24 18:46

    This feels a little too manual, but in practice I might do something like this:

    In [46]: mult[:] = sngl.loc[mult.index.get_level_values(2)].values
    
    In [47]: mult
    Out[47]: 
                 one       two     three      four
    10 1 a  1.175042  0.044014  1.341404 -0.223872
         b  0.216168 -0.748194 -0.546003 -0.501149
       2 a  1.175042  0.044014  1.341404 -0.223872
         b  0.216168 -0.748194 -0.546003 -0.501149
    20 1 a  1.175042  0.044014  1.341404 -0.223872
         b  0.216168 -0.748194 -0.546003 -0.501149
       2 a  1.175042  0.044014  1.341404 -0.223872
         b  0.216168 -0.748194 -0.546003 -0.501149
    

    That is, first select the elements we want to use to index:

    In [64]: mult.index.get_level_values(2)
    Out[64]: Index(['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'], dtype='object')
    

    Then use these to index into sngl:

    In [65]: sngl.loc[mult.index.get_level_values(2)]
    Out[65]: 
            one       two     three      four
    a  1.175042  0.044014  1.341404 -0.223872
    b  0.216168 -0.748194 -0.546003 -0.501149
    a  1.175042  0.044014  1.341404 -0.223872
    b  0.216168 -0.748194 -0.546003 -0.501149
    a  1.175042  0.044014  1.341404 -0.223872
    b  0.216168 -0.748194 -0.546003 -0.501149
    a  1.175042  0.044014  1.341404 -0.223872
    b  0.216168 -0.748194 -0.546003 -0.501149
    

    and then we can use .values to throw away the indexing information and just get the raw array to fill with.

    It's not very elegant, but it's straightforward.

    0 讨论(0)
提交回复
热议问题