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。
Series.str.replace(pat,repl,n = -1,case = None,flags = 0,regex = True)[源代码]
用其他字符串替换在Series / Index中出现的pattern / regex。等效于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
观察:
我改变了你的正则表达式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句