sssky
sssky

Reputation: 21

how to merge a multiIndex dataframe with a singleIndex dataframe, and keep the resulting dataframe multiIndexed

how to merge a multiIndex dataframe with a singleIndex dataframe, and keep the resulting dataframe multiIndexed

so i have dfA and dfB dfA:

fir    A      B    C
sec    Aa Ab  Ba   Ca  Cb
ind
1      1  2   2    2   1
2      1  2   2    2   1
4      1  2   2    2   1

dfB

ind
1
2
3
4
5

I want the result to be multiIndexed like:

fir    A      B    C
sec    Aa Ab  Ba   Ca  Cb
ind
1      1  2   2    2   1
2      1  2   2    2   1
3      0  0   0    0   0
4      1  2   2    2   1
5      0  0   0    0   0

I did a simple merge

dfA = pd.merge(dfB,dfA,how='left',on='ind').fillna(0)

I would have the result dfA as:

   ind (A,Aa)(A,Ab)(B,Ba)(C,Ca)(C,Cb)
0   1    2     2     2     2     1
1   2    2     2     2     2     1
2   3    0     0     0     0     0
3   4    2     2     2     2     1
4   5    0     0     0     0     0

the columns got flatten,i want to keep them multiIndexed

Upvotes: 0

Views: 38

Answers (1)

mozway
mozway

Reputation: 260335

Just reindex dfA on axis=0:

dfA.reindex(dfB['ind'], fill_value=0)

Output:

fir  A     B  C   
sec Aa Ab Ba Ca Cb
ind               
1    1  2  2  2  1
2    1  2  2  2  1
3    0  0  0  0  0
4    1  2  2  2  1
5    0  0  0  0  0

Upvotes: 1

Related Questions