简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM