python-3.x - 使用 python 替换数据框中列的多个字符

标签 python-3.x

我试图同时用一个字符替换多个字符,但我做不到

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/

相关文章:

python - 如何修复打印语句,使其在一行而不是两行?

python - "Inheriting ' 使用 SQLAlchemy declarative_base() 在 VS 代码中的基础 ', which is not a class"

python - 将列表函数应用于 itertools.groupby 中的嵌套生成器

Python - 两个数字的总和程序错误

python - 在 python 中使用 getattr

python - 我如何声明我的类(class)以便我可以像这样访问

python - 如何在 Python (cuPy/Numpy) 中将行与相应的列相乘?

python - 使用 python 3 在终端中打印 unicode 字符

python - Python中检查是否存在奇怪IP(不在白名单中的IP)的脚本函数

python - Python3队列: When can a blocking wait with no timeout return None?