简体   繁体   中英

How to replace specific data of one df with another df based on a dictionary having row and column info

suppose I have 2 df

df1
   A       B       C
0  1   Apple     WED
1  2  Pineapple  JYT
2  3    Tea      SDF

df2
   A       B       C
0  1   Apple     ABS
1  2  Banana     JYT
2  3    Cake     SDF
3  4   Apple     ABS
4  5    Cake     JYT
5  6    Cake     SDF

I want to replace df2 data with df1 based on a dict having values of column A . dict = {B:[2,3],C:[1]}

new df df3 will be

   A       B       C
0  1   Apple     WED
1  2  Pineapple  JYT
2  3    Tea      SDF
3  4   Apple     ABS
4  5    Cake     JYT
5  6    Cake     SDF

I tried by using iloc but failed.

First dont use dict for variable name, because python code word. Then extract values from first df1 to new DataFrame for only matched values and use DataFrame.update with set A to index for both DataFrame s:

d = {'B':[2,3],'C':[1]}

df11 = df1.set_index('A')
df12 = pd.concat({k:df11.loc[v, k] for k, v in d.items()}, axis=1)


df22 = df2.set_index('A')
df22.update(df12)
df = df22.reset_index()
print (df)
   A          B    C
0  1      Apple  WED
1  2  Pineapple  JYT
2  3        Tea  SDF
3  4      Apple  ABS
4  5       Cake  JYT
5  6       Cake  SDF

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