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

clstaudt

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

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

根据另一列(Python Pandas)的值在列中添加一部分字符串

使用值从另一列中删除字符串的一部分

用与对象数组匹配的值替换字符串的一部分?

将字符串的一部分从一列连接到另一列

R:将一列中的一部分字符串替换为data.table中另一列中的字符串

用其他列的值pandas + python替换字符串的一部分

用python中数据帧中的值替换字符串的一部分

Python 3用dict中的数据替换字符串的一部分

用mutate替换字符串的一部分(在管道中)

用PHP中的Regex替换字符串的一部分

更新列值,替换字符串的一部分

熊猫用字典中的值替换字符串的一部分

替换字符串中以逗号分隔列表一部分的值。的PHP

熊猫:从不同列中的元素替换字符串的一部分

用C中的另一个子字符串替换字符串的一部分

替换字符串的一部分

如何更改列中的字符串值,保存其中的一部分?

树枝用所选字符替换字符串的一部分

如何根据Oracle中另一列的内容删除列中的一部分字符串

使用列中的一部分字符串来计算并填充pandas数据框中的另一列

将列中的一部分字符串复制到MYSQL中的另一部分

根据R中另一列的一部分更改列的值

从数据文件的一列中删除点后的字符串的最后一部分

用已知的开始和结尾替换字符串的一部分

用 sed 替换字符串的一部分

用sed替换字符串的一部分

用sed替换字符串的一部分

用空字符串替换HTML页面的一部分