微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

假设我有两个原始的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

解决方法:

合并后使用np.where和isin更新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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐