【问题标题】:Replacing strings using regex using Pandas使用 Pandas 使用正则表达式替换字符串
【发布时间】: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


【解决方案1】:

replace 似乎不支持将方法作为替换参数。因此,您所能做的就是隐式导入re 库并使用apply

>>> import re
>>> #... your code ...
>>> ser.apply(lambda row: re.sub(patt, repl, row))
0    Åland Islands
1          Réunion
2        Zimbabwe"
dtype: object

【讨论】:

  • 事实证明(截至 Pandas 0.22)Series.str.replace 确实接受可调用对象,但 Series.replace 不接受。
  • @xnx 您的问题是关于如何替换数据框中的所有值。因此我的回答。
【解决方案2】:

Pandas 中有两个replace 方法。

直接作用于系列的可以采用正则表达式模式字符串或编译的正则表达式,并且可以就地执行,但不允许替换参数是可调用的。您必须设置 regex=True 并使用原始字符串。

与:

import re
import pandas as pd
ser = pd.Series(['Aland Islands !Åland Islands', 'Reunion !Réunion', 'Zimbabwe'])

是的:

ser.replace(r'.*!(.*)', r'\1', regex=True, inplace=True)
ser.replace(r'.*!', '', regex=True, inplace=True)
regex = re.compile(r'.*!(.*)', inplace=True)
ser.replace(regex, r'\1', regex=True, inplace=True)

没有:

repl = lambda m: m.group(1)
ser.replace(regex, repl, regex=True, inplace=True)

还有一个,用作Series.str.replace。这个接受一个可调用的替换,但不会就地替换并且不采用regex 参数(尽管可以使用正则表达式模式字符串):

是的:

ser.str.replace(r'.*!', '')
ser.str.replace(r'.*!(.*)', r'\1')
ser.str.replace(regex, repl)

没有:

ser.str.replace(regex, r'\1')
ser.str.replace(r'.*!', '', inplace=True)

我希望这对那里的人有所帮助。

【讨论】:

    【解决方案3】:

    试试这个 sn-p:

    pattern = r'(.*)!'
    ser.replace(pattern, '', regex=True)
    

    在您的情况下,您没有设置regex=True,因为它默认为 false。

    【讨论】:

      猜你喜欢
      • 2015-02-27
      • 1970-01-01
      • 2017-08-07
      • 2015-05-21
      • 2012-07-11
      • 1970-01-01
      相关资源
      最近更新 更多