嗨, 我有两个数据帧,我想更改第一个数据帧中的值,其中两个数据帧中的 ID 相同, 假设我有:
df1 = [ID price
1 200
4 300
5 120
7 230
8 110
9 90
12 180]
和
df2 = [ID price count
3 340 27
4 60 10
5 290 2]
替换后:
df1 = [ID price
1 200
4 60
5 290
7 230
8 110
9 90
12 180]
我的第一次尝试:
df1.loc[df1.ID.isin(df2.ID),['price']] = df2.loc[df2.ID.isin(df1.ID),['price']].values
但这是不正确的。
最佳答案
假设ID
是索引(或者可以设置为索引),那么你可以直接更新
:
In []:
df1.update(df2)
df1
Out[]:
price
ID
1 200.0
4 60.0
5 290.0
7 230.0
8 110.0
9 90.0
12 180.0
如果您需要set_index()
:
df = df1.set_index('ID')
df.update(df2.set_index('ID'))
df1 = df.reset_index()
关于python - 如何根据 pandas 中的另一个数据帧更改数据帧中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886300/