【问题标题】:Replace values from one column with another column Pandas DataFrame用另一列 Pandas DataFrame 替换一列中的值
【发布时间】:2019-07-16 17:20:12
【问题描述】:

我有一个带有 id 作为字符串的 pandas 数据框 df: 我正在尝试创建 new_claim 和 new_description 列

我找到的最接近的 SO 是 Efficiently replace part of value from one column with value from another column in pandas using regex?,但这使用了拆分部分,并且由于描述发生了变化,我无法一概而论。

我可以一劳永逸

date_reg = re.compile(r'\b'+df['old_id'][1]+r'\b')

df['new_claim'] = df['claim'].replace(to_replace=date_reg, value=df['external_id'], inplace=False)

如果我有

date_reg = re.compile(r'\b'+df['claim']+r'\b')

然后我得到“TypeError: 'Series' 对象是可变的,因此它们不能被散列”

我采取的另一种方法

df['new_claim'] = df['claim']

for i in range(5):
    old_id = df['old_id'][i]
    new_id = df['external_id'][i]

    df['new_claim'][i] = df['claim'][i].replace(to_replace=old_id,value=new_id)

产生类型错误:replace() 不接受关键字参数

【问题讨论】:

    标签: python regex pandas replace


    【解决方案1】:

    仅使用方法pandas.replace():

    df.old_id = df.old_id.fillna(0).astype('int')
    
    list_old = list(map(str, df.old_id.tolist()))
    list_new = list(map(str, df.external_id.tolist()))
    
    df['new_claim'] = df.claim.replace(to_replace=['Claim ID: ' + e for e in list_old], value=['Claim ID: ' + e for e in list_new], regex=True)
    df['new_description'] = df.description.replace(to_replace=['\* ' + e + '\\n' for e in list_old], value=['* ' + e + '\\n' for e in list_new], regex=True)
    

    产生以下输出:

    【讨论】:

    • 谢谢,当 old_id = 2838976 和 external_id = 102372949 新声明变为声明 ID:102371023948109 时,我得到了一个意外的输出,在大多数情况下它按预期工作
    • @MattS,问题是较小的模式匹配较大的 ID。例如,在 1111 id 中找到值 11。
    • 如果你可以发布一个真实的案例测试,我们可以尝试找到另一种模式来过滤,比如使用分号作为值的一部分。
    • 嗨@MattS,我已经改进了匹配的模式。问题是空的 old_id。如果一切正确,请接受并支持我的回答! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2017-02-15
    • 2020-11-09
    • 2022-11-25
    • 1970-01-01
    • 2014-06-12
    相关资源
    最近更新 更多