python - 用列/系列中的值替换 pandas 子字符串

标签 python pandas

我正在尝试用 pandas 列中的值替换 Pandas 子字符串。这个问题以前没有人回答过。

我尝试使用 .replace() 方法,但它抛出以下错误:

TypeError Traceback (most recent call last) in ----> 1 df['name'].str.replace('(C)', df.name2)

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/strings.py in wrapper(self, *args, **kwargs) 1841 ) 1842
raise TypeError(msg) -> 1843 return func(self, *args, **kwargs) 1844 1845 wrapper.name = func_name

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/strings.py in replace(self, pat, repl, n, case, flags, regex) 2714 def replace(self, pat, repl, n=-1, case=None, flags=0, regex=True):
2715 result = str_replace( -> 2716 self._parent, pat, repl, n=n, case=case, flags=flags, regex=regex 2717 ) 2718 return self._wrap_result(result)

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/strings.py in str_replace(arr, pat, repl, n, case, flags, regex) 597 # Check whether repl is valid (GH 13438, GH 15055) 598 if not (is_string_like(repl) or callable(repl)): --> 599 raise TypeError("repl must be a string or callable") 600 601 is_compiled_re = is_re(pat)

TypeError: repl must be a string or callable

data = {'id': [1, 2, 3, 4], 'name': ['name1 (C)', 'name2 (B)', 'name3', 'name4'],
        'name2':['Jane','Abbie','Luke','Peter']}


df = pd.DataFrame(data)

df['name'].str.replace('\(C\)', df.name2)

预期结果:

    id  name    name2
0   1   name1 Jane  Jane
1   2   name2 Abbie Abbie
2   3   name3   Luke
3   4   name4   Peter

最佳答案

您需要 python re.sub 和 listcomp

import re

df['new_name'] = [re.sub(r'\(\w+\)', r, s) for r, s in zip(df.name2, df.name)]

Out[280]:
   id       name  name2     new_name
0   1  name1 (C)   Jane   name1 Jane
1   2  name2 (B)  Abbie  name2 Abbie
2   3      name3   Luke        name3
3   4      name4  Peter        name4

关于python - 用列/系列中的值替换 pandas 子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58806272/

相关文章:

python - Pandas:当组中的值落在某个范围内时,将组保留在数据中

python - 使用 python 中 statsmodels 的 ExponentialSmoothing 通过三重指数平滑进行预测

python - 汇总分组 Pandas 数据框中的行并返回 NaN

python - 删除列表中字符串的所有扩展名

python - 将列表的每个元素附加到文件行的末尾

python - 在c中读取python的全局变量

python - 减去 pandas 数据框,同时保留一些列完好无损

python - 从远程机器执行长时间运行的配置单元查询

python - AWS Glue Python ETL : logger messages appear in the error cloudwatch stream

python - 对 Pandas 矩阵中的所有值进行排序