使用Pandas替换使用regex的字符串
在Pandas中,为什么不将任何包含感叹号的字符串替换为其后的内容使用Pandas替换使用regex的字符串,regex,python-3.x,pandas,replace,Regex,Python 3.x,Pandas,Replace,在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éunio
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
在第一种情况下,我做错了什么?试试这个片段:
pattern = r'(.*)!'
ser.replace(pattern, '', regex=True)
在您的情况下,您没有设置
regex=True
,因为默认情况下它是false。似乎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
熊猫中有两种
replace
方法
直接作用于序列的参数可以采用正则表达式模式字符串或编译的正则表达式,并且可以就地作用,但不允许替换参数是可调用的。必须设置regex=True
并使用原始字符串
与:
是的:
否:
还有一个,用作Series.str.replace
。此函数接受可调用的替换,但不会就地替换,也不会接受regex
参数(尽管可以使用正则表达式模式字符串):
是的:
否:
我希望这对其他人有所帮助。我认为您在第一条语句中缺少了
regex=True
。import re
并使用ser.apply(lambda row:re.sub(patt,repl,row))
证明(从0.22开始)Series.str.replace
接受可调用的,但是,Series.replace
没有。您的问题是如何替换数据帧中的所有值。这就是我的答案。
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)
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)