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
r"{.+?}"
或r"{[^{}]*}"
模式。 - Wiktor Stribiżew