我正在尝试用 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/