繁体   English   中英

用另一列 Pandas DataFrame 替换一列中的值

[英]Replace values from one column with another column Pandas DataFrame

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

示例 df

我发现的最接近的 SO 是使用正则表达式有效地用熊猫中另一列的值替换一列中的部分值? 但这使用了拆分部分,并且由于描述发生了变化,我无法一概而论。

我可以跑一次

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() 没有关键字参数

仅使用方法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)

产生以下输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM