Mquinteiro
Mquinteiro

Reputation: 1080

pandas add multiple columns (that not exists) to row of dataframe

Supose this code

a = pd.DataFrame([1,2,3])

if I do

a.loc[0,'A']=3

I get:

   0   A
0  1   3
1  2 NaN
2  3 NaN

Now suppose that:

a = pd.DataFrame([1,2,3])
b=pd.DataFrame([[5,4],[6,3],[7,2]],columns=['B','C'])

Is there a way to do a[1,'A','B']=b[2] that gets as result

   0   B   C
0  1 NaN NaN
1  2   7   2
2  3 NaN NaN

Update: I have change a bit the question because the answers supose that a and b have same indexes and it is not.

Upvotes: 0

Views: 321

Answers (3)

BENY
BENY

Reputation: 323396

How about pd.concat:

pd.concat([a,b.loc[b.index==0,:]],axis=1)

Out[53]: 
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

Upvotes: 1

Zero
Zero

Reputation: 77027

You could use join on a with required row of b

In [150]: a.join(b.loc[0:0])
Out[150]:
   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

Upvotes: 4

Xukrao
Xukrao

Reputation: 8644

One possibility:

import pandas as pd

a = pd.DataFrame([1, 2, 3])
b = pd.DataFrame([[5, 4], [6, 3], [7, 2]], columns=['B', 'C'])

a.loc[0, 'B'] = b.loc[0, 'B']
a.loc[0, 'C'] = b.loc[0, 'C']

which gives as a:

   0    B    C
0  1  5.0  4.0
1  2  NaN  NaN
2  3  NaN  NaN

Upvotes: 1

Related Questions