gpt4 book ai didi

Python - Pandas - 根据其他列中的值替换列中的字符串 - 处理子字符串

转载 作者:行者123 更新时间:2023-12-01 06:24:36 25 4
gpt4 key购买 nike

基于以下帖子: Python - Pandas - Replace a string from a column based on the value from other column

我也在做一些类似的事情,但我面临着新的挑战。我使用与上一篇文章相同的示例。

新的挑战由子字符串组成。

假设我有以下数据框:

enter image description here

我正在尝试用 col2 中的值替换 col2 上存在于 col0 上的值。

如果我使用代码(与上一篇文章相同):

df['col3'] = df['col1'].replace(df['col0'].values, df['col2'].values, regex = True)

我将返回以下数据框:

enter image description here

我正在尝试的是以下内容:

enter image description here

我可以在 .values 上添加更多精度来实现此目的吗?

谢谢!

最佳答案

使用 re.sub 替换 DataFrame.apply 中的行:

import re

df['col3'] = df.apply(lambda x: re.sub(x['col0'],x['col2'],x['col1']), axis=1)

或者在列表理解中:

df['col3'] = [re.sub(a,c,b) for a,b,c in df[['col0','col1','col2']].to_numpy()]
<小时/>
print (df)
col0 col1 col2 col3
0 Table 1 Tablename: Table 1 Table A Tablename: Table A
1 Table 2 Tablename: Table 2 Table B Tablename: Table B
2 Table 2_1 Tablename: Table 2_1 Table C Tablename: Table C

关于Python - Pandas - 根据其他列中的值替换列中的字符串 - 处理子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60225535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com