如果数据帧中的行存在于另一个数据帧中,则修改该行

2024-09-24 06:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧DfMasterDfError

DfMaster看起来像:

     Id           Name Building
0  4653     Jane Smith        A
1  3467    Steve Jones        B
2    34        Kim Lee        F
3  4567     John Evans        A 
4  3643   Kevin Franks        S
5   244  Stella Howard        D

而且DfError看起来像

     Id           Name Building
0  4567     John Evans        A 
1   244  Stella Howard        D

DfMaster中,我想将记录的Building值更改为DD,如果它出现在DfError数据帧中。因此,我期望的输出是:

     Id           Name Building
0  4653     Jane Smith        A
1  3467    Steve Jones        B
2    34        Kim Lee        F
3  4567     John Evans        DD 
4  3643   Kevin Franks        S
5   244  Stella Howard        DD

我尝试使用以下方法:

DfMaster.loc[DfError['Id'], 'Building'] = 'DD'

但是,我得到一个错误:

KeyError: "None of [Int64Index([4567,244], dtype='int64')] are in the [index]"

有人能告诉我我做错了什么吗

谢谢


Tags: 数据nameidjohnddstevesmithbuilding
2条回答

使用^{}试试这个

import numpy as np
errors = list(dfError['id'].unqiue())
dfMaster['Building_id'] = np.where(dfMaster['Building_id'].isin(errors),'DD',dfMaster['Building_id'])

DataFrame.loc要求您输入索引或布尔序列,而不是列中的值

我相信这应该可以做到:

DfMaster.loc[DfMaster['Id'].isin(DfError['Id']), 'Building'] = 'DD'

基本上,它告诉我们: 对于DfError['Id']中存在Id值的所有行,将'Building'的值设置为'DD'

相关问题 更多 >