我试图同时用一个字符替换多个字符,但我做不到
df = pandas.DataFrame({"Col1":["A", "B", "ABC", "D", "AB"], "Col2":["H", "I", "J", "K", "L"]})
>>> df
Col1 Col2
0 A H
1 B I
2 ABC J
3 D K
4 AB L
替换数据框中某列的多个字符
df['Col1'] = df['Col1'].str.replace(['C','D'],'W')
>>>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Laura\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\strings.py", line 1954, in wrapper
return func(self, *args, **kwargs)
File "C:\Users\Laura\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\strings.py", line 2777, in replace
self._parent, pat, repl, n=n, case=case, flags=flags, regex=regex
File "C:\Users\Laura\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\strings.py", line 713, in str_replace
compiled = re.compile(pat, flags=flags)
File "C:\Users\Laura\AppData\Local\Programs\Python\Python37-32\lib\re.py", line 234, in compile
return _compile(pattern, flags)
File "C:\Users\Laura\AppData\Local\Programs\Python\Python37-32\lib\re.py", line 276, in _compile
return _cache[type(pattern), pattern, flags]
TypeError: unhashable type: 'list'
如果有效的话可以单独使用,但我认为这不是最好的方法
df['Col1'] = df['Col1'].str.replace('C','W')
df['Col1'] = df['Col1'].str.replace('D','W')
>>> df
Col1 Col2
0 A H
1 B I
2 ABW J
3 W K
4 AB L
我怎样才能同时或更有效地做到这一点?
最佳答案
str.replace中的字符串是正则表达式模式,因此您可以利用它:
df['Col1'] = df['Col1'].str.replace(r'C|D','W')
print(df)
打印:
Col1 Col2
0 A H
1 B I
2 ABW J
3 W K
4 AB L
关于python-3.x - 使用 python 替换数据框中列的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61687030/