我有一个 pandas 数据框 dfdata,其中有一个字段“fieldname”,其中包含字符串数据,以及诸如“then value)”之类的子字符串条目。我想用“然后值结束)”之类的内容替换这些条目。问题是不同行的“值”不同,并且字符串包含多个“)”。所以 str.replace 不起作用。我在想也许是带有通配符的 re.sub 之类的东西,但我需要通配符值显示在替换中。我想我可能需要写一个循环。有谁知道一个巧妙的方法来做到这一点?我在下面有示例数据和输出。
Example Data:
import pandas as pd
dfdata = pd.DataFrame({'fieldname1': ['Bob', 'Jane'],
'fieldname2': ['Other words when spaghetti then turnip), do this)', 'Different other words when tomato then ketchup)']})
Example Output:
import pandas as pd
dfdata = pd.DataFrame({'fieldname1': ['Bob', 'Jane'],
'fieldname2': ['Other words when spaghetti then turnip end), do this)', 'Different other words when tomato then ketchup end)']})
最佳答案
IIUC:
In [36]: dfdata['fieldname2'] = \
dfdata['fieldname2'].str.replace(r'(\s*then\s*)(\w+)\)', r'\1\2 end)')
In [37]: dfdata
Out[37]:
fieldname1 fieldname2
0 Bob Other words when spaghetti then turnip end), do this)
1 Jane Different other words when tomato then ketchup end)
关于python - Pandas 模式匹配添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44806909/