Max K
Max K

Reputation: 171

appending an MultiIndex DataFrame to an existing one with the ['key'] operator

I'm trying to concat two dataframes without using concat, but the ['key'] operator.

import pandas as pd
        
df1 = pd.DataFrame(np.random.normal(size=(6,)).reshape((3,2)), columns=pd.MultiIndex.from_product([['pca'], ["pca1", "pca2"]]))
df2 = pd.DataFrame(np.random.normal(size=(6,)).reshape((3,2)), columns=pd.MultiIndex.from_product([['someNames'], ["mnf1", "mnf2"]]))

my goal would be to do:

df1['mnf'] = df2

But pandas does not seem to like this. Is there a way to concat those two dataframes without using concat?

So:

       pca          
       pca1      pca2
0  0.754675  1.868685
1 -1.861651 -0.048236
2 -0.797750  0.388400
    
      someNames          
      nmf1      nmf2
0    1.671707  0.452155
1    0.861315 -0.100849
2    1.056616 -0.852532

And my result should look like:

        pca                 nmf          
       pca1      pca2      nmf1      nmf2
0  1.671707  0.452155  1.671707  0.452155
1  0.861315 -0.100849  0.861315 -0.100849
2  1.056616 -0.852532  1.056616 -0.852532

Cheers

Edit: In my previous version I mixed up rows and columns

Upvotes: 0

Views: 27

Answers (1)

Kuldip Chaudhari
Kuldip Chaudhari

Reputation: 1112

try this

result = df1.copy(deep=True)
result[df2.columns] = df2

Upvotes: 1

Related Questions