python - 如果它们具有相同列的值,如何更新 pandas 列?

标签 python pandas dataframe

比方说,我有两个像这样的原始 DataFrame:

df1 = pd.DataFrame({"ID": [101, 102, 103], "Price":[12, 33, 44], "something":[12,22,11]})
df2 = pd.DataFrame({"ID": [101, 103], "Price":[122, 133]})

它显示如下:

    ID  Price  something
0  101     12          12
1  102     33          22
2  103     44          11

    ID  Price
0  101    122
1  103    133

由于我没有为任何列设置任何索引,我想知道如果两个 DataFrame 具有相同的 ID,我该如何更新 df1。对于这个示例,我希望我能得到这样的结果:

    ID  Price  something
0  101     122          12
1  102     33           22
2  103     133          11

你可以看到,我只关心价格栏。这是我现在尝试过的:

pd.concat([df1,df2]).drop_duplicates(['ID'],keep='last') 

但它只是告诉我:

    ID  Price  something
1  102     33        22.0
0  101    122         NaN
1  103    133         NaN

我不想更改任何其他列值。

我想保持 df1 的行顺序。

更新

运行答案代码后,我发现列的顺序会改变,因为我们正在使用 reset_index,一些关于索引的东西。所以我希望有人能指出我如何保持我的 DataFrame 的原始位置。现在,它看起来像下面这样:

In [180]: df1 = pd.DataFrame({"ss":[12,22,11], "ID": [101, 102, 103], "Price":[12, 33, 44], "something":[12,22,11]}) 
     ...: df2 = pd.DataFrame({"ID": [101, 103], "Price":[122, 133]}) 

                                                                                                                                                                     

In [181]: df1.set_index('ID',inplace=True) 
     ...: df1.update(df2.set_index('ID')) 
     ...: df1.reset_index(inplace=True)                                                                                                                                                                                                       

In [182]: df1                                                                                                                                                                                                                                 
Out[182]: 
    ID  ss  Price  something
0  101  12  122.0         12
1  102  22   33.0         22
2  103  11  133.0         11

最佳答案

merge 后使用 np.whereisin 更新 df1 中的价格

df1.Price=np.where(df1.ID.isin(df2.ID),df1.merge(df2,on='ID',how='left')['Price_y'],df1.Price)

df1

    ID  Price  something
0  101  122.0          12
1  102   33.0          22
2  103  133.0          11

使用更新:

df1.set_index('ID',inplace=True)
df1.update(df2.set_index('ID'))
df1.reset_index(inplace=True)

df1 
    ID  Price  something
0  101  122.0          12
1  102   33.0          22
2  103  133.0          11

关于python - 如果它们具有相同列的值,如何更新 pandas 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389781/

相关文章:

python - 动态格式化字符串

python - 如何在 Seaborn 按 YearMonth 订购 X 轴

python - 从分组数据框中获取百分位数

python - 分配给 pandas DataFrame 的切片

python - 按列值对数据帧进行索引

python - 如何更改 $$ 中的字体,它是 python 中的数学形式

python - 如何使用正则表达式解析化学式?

python - 与复数相关的点积

R - 并非所有元素都返回(for 循环)

dataframe - Pyspark 收集列表