Pandas图案匹配添加纹理

2024-03-29 11:46:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe dfdata,它有一个字段“fieldname”,其中包含字符串数据,子字符串条目像“then value”。我想用类似“then value end”的内容替换这些条目。问题是不同行的“值”不同,字符串包含多个“)”。所以呢结构更换不起作用。我在想也许回复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)']})

Tags: 数据字符串importpandasvalueexampleas条目
1条回答
网友
1楼 · 发布于 2024-03-29 11:46:44

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)

相关问题 更多 >