mkmostafa
mkmostafa

Reputation: 3171

pandas assign values from one frame to corresponding columns in another in selected rows

DF1
|col1 |  col2 |  col3 |
  12     v1      v12
  3      v3      v13
  5      v5      v14
  7      v10     v15

DF2
|col2| col3|
  x1  y2
  x2  y1

output DF1
|col1 |  col2 |  col3 |
  12     x2      y1
  3      v3      v13
  5      v5      v14
  7      x1     y2

I want to set the rows 7,12 inDF1 to the values of DF2 without explicitly specifying the columns

something like DF1[7,12] = DF2

Upvotes: 0

Views: 28

Answers (2)

sacuL
sacuL

Reputation: 51395

Using only a .loc statement:

DF1.loc[DF1.col1.isin([12,7]), 'col2'] = DF2.col2.values

Returns:

>>> DF1
   col1 col2 col3
0    12   x1  v12
1     3   v3  v13
2     5   v5  v14
3     7   x2  v15

Upvotes: 0

BENY
BENY

Reputation: 323326

You need to using update

df2.index=[0,3]# change the index you want to update in df1, then just using update 
df1.update(df2)
df1
Out[404]: 
   col1 col2 col3
0    12   x1   y2
1     3   v3  v13
2     5   v5  v14
3     7   x2   y1

Upvotes: 5

Related Questions