【问题标题】:replacing part of a string with value from another column用另一列中的值替换字符串的一部分
【发布时间】:2019-08-08 00:16:42
【问题描述】:

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

【问题讨论】:

    标签: python regex string pandas


    【解决方案1】:

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

    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
    

    观察:

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

    【讨论】:

    • 您最好使用r"{.+?}"r"{[^{}]*}" 模式。
    • 谢谢,@WiktorStribiżew,你是对的!我没有过多强调正则表达式部分。刚刚编辑。
    【解决方案2】:

    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 - 当然,最好测试一下,str 在 pandas 中的操作很慢。
    猜你喜欢
    • 2020-11-03
    • 2022-11-25
    • 2020-11-09
    • 2023-03-20
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多