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

4

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
2个回答

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

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

用其他字符串替换Series/Index中模式/正则表达式的出现。相当于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

观察:
我稍微修改了你的正则表达式。

最好使用 r"{.+?}"r"{[^{}]*}" 模式。 - Wiktor Stribiżew
谢谢,@WiktorStribiżew,你是正确的!我没有给正则表达式部分太多的重视。刚刚进行了编辑。 - Daniel Labbe

4
使用列表推导式与re.sub结合使用,尤其是在性能方面很重要时:
import re

df['new'] = [re.sub(r"{.*?}", b, a) for a, b in zip(df['descr'], df['replacement'])]
print (df)
                        descr replacement              new
0  This: {should be replaced}   with this  This: with this
1                This: {data}         aaa        This: aaa

离开pandas使用列表推导式比使用pandas.Series.replace性能更好吗? - clstaudt
@clstaudt - 当然,最好测试一下,在pandas中进行的“str”操作速度较慢。 - jezrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接