将一列中的值替换为另一列Pandas DataFrame

问题描述 投票:1回答:1

我有一个pandas数据帧df,其中id为字符串:我正在尝试创建new_claim和new_description列

example df

最近的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:'系列'对象是可变的,因此它们不能被散列”

我采取的另一种方法

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)

给出了TypeError:replace()不带关键字参数

python regex pandas replace
1个回答
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)

产生以下输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.