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/