带有通配符的pandas.DataFrame.replace

时间:2016-07-29 15:31:35

标签: python regex pandas replace dataframe

pandas.DataFrame.replace正则表达式是否替换支持通配符和“捕获组”?

例如,将([A-Z])(\w+)替换为\2\1

支持哪种正则表达式? Perl的正则表达式是否受支持?例如,可以用([A-Z])(\w+)替换\l\1\2\l将下一个字符更改为小写。)

更新

正如史蒂夫指出的那样,根据Python documentation,它应该有效,但以下内容并没有给出我的预期:

df = pd.DataFrame({'A': np.random.choice(['foo', 'bar'], 100),
                   'B': np.random.choice(['one', 'two', 'three'], 100),
                   'C': np.random.choice(['I1', 'I2', 'I3', 'I4'], 100),
                   'D': np.random.randint(-10,11,100),
                   'E': np.random.randn(100)})
df.replace("f(.)(.)","b\1\2", regex=True,inplace=True)

怎么了?

THX

1 个答案:

答案 0 :(得分:3)

根据pandas documentation

  

使用re.sub。进行正则表达式替换。替换re.sub的规则是相同的。

所以,是的,任何可以使用Python re.sub(例如\1)执行的替换也可以使用pandas.DataFrame.replace执行。有关详细信息,请参阅Python documentation