简体   繁体   中英

substitue values of one dataframe from values of another dataframe based on condition

I have a df which looks like

floor id p1 p2 p3
L1     1  5  6  7
L1     2  5  8  3
L2     1  4  2  1
L2     2  4  5  4

and df2

floor id p1 p2 p4
L1     1  6  6  5
L1     2  9  8  5 
L2     1  5  5  5
L2     2  4  5  5

How do I replace the values of p1 and p2 in my df for particular floor and id with the values the respective values from df2?

We can also use DataFrame.merge

df1 = (df1[df1.columns.difference(['p1','p2'])].merge(df2,
                                                      on =['floor','id'],
                                                      how ='left')
                                               .fillna(df1)[df1.columns])
print(df1)
  floor  id  p1  p2  p3
0    L1   1   6   6   7
1    L1   2   9   8   3
2    L2   1   5   5   1
3    L2   2   4   5   4

Merge can be used for this particular problem:

# left join
df = (df.merge(df2, left_on=['floor', 'id'], how='left', right_on=['floor', 'id'])
# fill missing values with corresponding original df values
df['p1_y'] = df['p1_y'].fillna(df['p1_x']).astype(int)
df['p2_y'] = df['p2_y'].fillna(df['p2_x']).astype(int)

# drop unnecessary columns
df.drop(['p1_x', 'p2_x', 'p4'], axis=1, inplace=True)
df.rename(columns={'p1_y': 'p1', 'p2_y': 'p2'}, inplace=True)

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