【发布时间】:2018-10-05 19:51:05
【问题描述】:
在 Pandas 中,为什么以下内容不替换任何包含感叹号的字符串?
In [1]: import pandas as pd
In [2]: ser = pd.Series(['Aland Islands !Åland Islands', 'Reunion !Réunion', 'Zi
...: mbabwe'])
In [3]: ser
Out[3]:
0 Aland Islands !Åland Islands
1 Reunion !Réunion
2 Zimbabwe
dtype: object
In [4]: patt = r'.*!(.*)'
In [5]: repl = lambda m: m.group(1)
In [6]: ser.replace(patt, repl)
Out[6]:
0 Aland Islands !Åland Islands
1 Reunion !Réunion
2 Zimbabwe
dtype: object
而对匹配子字符串的直接引用确实有效:
In [7]: ser.replace({patt: r'\1'}, regex=True)
Out[7]:
0 Åland Islands
1 Réunion
2 Zimbabwe
dtype: object
在第一种情况下我做错了什么?
【问题讨论】:
-
我认为您在第一条语句中缺少
regex=True。 -
import re并使用ser.apply(lambda row: re.sub(patt, repl, row))
标签: regex python-3.x pandas replace