pandas 从另一个df替换dataframe中的值

r1wp621o  于 2023-04-10  发布在  其他
关注(0)|答案(2)|浏览(116)

DF1:

ID  PRICE  WEIGHT STOCK 
1     20     100    30
2     30     200    10
3     40     300    20

DF2:

ID   WEIGHT   STOCK
2      90       40
3      400      70

我想用df2中的正确值替换df1中的值
我试图得到这样的结果:

ID  PRICE  WEIGHT STOCK 
1     20     100   30
2     30     90    40
3     40     400   70
bpsygsoo

bpsygsoo1#

可能的解决方案:

out = df1.set_index('ID')
out.update(df2.set_index('ID'))
out = out.reset_index()

输出:

ID  PRICE  WEIGHT  STOCK
0   1     20   100.0   30.0
1   2     30    90.0   40.0
2   3     40   400.0   70.0
zujrkrfu

zujrkrfu2#

import pandas as pd

df1 = pd.DataFrame({'ID': [1, 2, 3],
                   'PRICE': [20, 30, 40],
                   'WEIGHT': [100, 200, 300],
                   'STOCK': [30, 10, 20],
                   })

df2 = pd.DataFrame({'ID': [2, 3],
                   'WEIGHT': [90, 400],
                   'STOCK': [40, 70],
                   })

df2 = df2.set_index('ID')
df1 = df1.set_index('ID')
df1.loc[df2.index,['WEIGHT', 'STOCK']] = df2[['WEIGHT', 'STOCK']]

print(df1.reset_index())
ID  PRICE  WEIGHT  STOCK
0   1     20     100     30
1   2     30      90     40
2   3     40     400     70

相关问题