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

cls*_*udt 4 python regex string pandas

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

descr                        replacement
This: {should be replaced}   with this
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

Dan*_*bbe 5

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

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

将系列/索引中出现的模式/正则表达式替换为其他字符串。相当于 str.replace() 或 re.sub()。参数:

pat :字符串或编译的正则表达式

repl :字符串或可调用...

您可以直接使用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
Run Code Online (Sandbox Code Playgroud)

观察:

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