如果熊猫的列值相同,该如何更新?

时间:2019-03-28 03:34:47

标签: 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具有相同的df1时如何更新ID。对于此示例,我希望可以得到如下结果:

    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

2 个答案:

答案 0 :(得分:3)

np.where之后,使用isinmerge在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

使用update

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

答案 1 :(得分:1)

另一个可能的解决方案是使用combine_first()

df2.set_index(['ID']).combine_first(df1.set_index(['ID', 'something'])).reset_index()

也可以使用isin()

df1.loc[df1.ID.isin(df2.ID), ['Price']] = df2[['Price']].values
相关问题