python - 用另一列的值替换字符串的一部分

标签 python regex string pandas

pandas DataFrame 包含一列,其中包含描述和占位符,位于花括号中:

descr                        replacement
This: {should be replaced}   with this

任务是将花括号中的文本替换为同一行中另一列的文本。不幸的是,这并不像以下那样容易:

df["descr"] = df["descr"].str.replace(r"{*?}", df["replacement"])

~/anaconda3/lib/python3.6/site-packages/pandas/core/strings.py in replace(self, pat, repl, n, case, flags, regex)
   2532     def replace(self, pat, repl, n=-1, case=None, flags=0, regex=True):
   2533         result = str_replace(self._parent, pat, repl, n=n, case=case,
-> 2534                              flags=flags, regex=regex)
   2535         return self._wrap_result(result)
   2536 

~/anaconda3/lib/python3.6/site-packages/pandas/core/strings.py in str_replace(arr, pat, repl, n, case, flags, regex)
    548     # Check whether repl is valid (GH 13438, GH 15055)
    549     if not (is_string_like(repl) or callable(repl)):
--> 550         raise TypeError("repl must be a string or callable")
    551 
    552     is_compiled_re = is_re(pat)

TypeError: repl must be a string or callable

最佳答案

您的代码使用了 Pandas.Series.str.replace()它期望两个字符串执行替换操作,但第二个参数是一个系列。

Series.str.replace(pat, repl, n=-1, case=None, flags=0, regex=True)[source]

Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to str.replace() or re.sub(). Parameters:

pat : string or compiled regex

repl : string or callable ...

您可以直接使用 Pandas.Series.replace() 更正它方法:

df = pd.DataFrame({'descr': ['This: {should be replaced}'],
                   'replacement': 'with this'
                  })
>> df["descr"].replace(r"{.+?}", df["replacement"], regex = True)
0    This: with this

观察:

我改变了一些你的正则表达式。

关于python - 用另一列的值替换字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55207646/

相关文章:

regex - 字符串中单次出现的正则表达式

python - 在Python中选择列表的非空元素

python - 获取非测试模块的 pytest 回溯

c# - 正则表达式未找到所有匹配项 C#

python - 如何修复 lxml 中的 XSD 导入错误?

regex - 如何处理 Google App Engine app.yaml 中的尾部斜杠

编译打印字符串函数给出错误信息 - C

python - 如何正确传递要使用 python -c 执行的文字字符串 python 代码

python - 在 Ruby 或 Python 中解析 SVG 的库

python - 如何在pygame中绘制透明线