python - Pandas 模式匹配添加文本

标签 python loops pandas

我有一个 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/

相关文章:

python - 为什么python中有的包或函数首字母大写,有的不大写?

python - 在Python中迭代列表并连接字母顺序

PHP - 在数组中返回数组的值

python - 使用 Pandas MultiIndex 在 matplotlib 条形图中对标签进行分组

python - PIL/scipy.misc 中的 imresize 仅适用于 uint8 图像?有什么选择吗?

javascript - 非法使用 break 语句; javascript

json - 使用递归更改 json 中的值

python - 如何循环遍历 Pandas 数据框

python - 添加到 pandas 数据框的列在例如时不会粘住。写入 csv

python - 计算某些文本中多字子串的出现次数