![](/img/trans.png)
[英]Python - Pandas - Replace a string from a column based on the value from other column
[英]Python - Pandas - Replace a string from a column based on the value from other column - Dealing with substrings
基於以下帖子: Python - Pandas - 根據其他列的值替換列中的字符串
我也在做一些類似的事情,我面臨着新的挑戰。 我使用與上一篇文章相同的示例。
由子串組成的新挑戰。
想象一下,我有以下數據框:
我想要的是用 col2 中的值替換 col2 上存在的 col0 值。
如果我使用代碼(與上一篇文章相同):
df['col3'] = df['col1'].replace(df['col0'].values, df['col2'].values, regex = True)
我將返回以下數據框:
我正在嘗試的是以下一個:
我可以在 .values 上添加更多精度來實現這一點嗎?
謝謝!
使用re.sub
和DataFrame.apply
的行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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.