正则表达式字典中的Pandas DataFrame.replace无法正常工作,还是我犯了一些错误?

时间:2019-03-15 20:44:35

标签: python regex pandas

MMWE:

In [1]: df = pd.DataFrame(
            {'A': [0, 1, 2],
             'B': ['ba\nt', 'foo', 'bait'],
             'C': ['abc', 'ba\nr', 'xyz']}
        )
In [2]: df
Out[2]:     A   B       C
        0   0   ba\nt   abc
        1   1   foo     ba\nr
        2   2   bait    xyz

In [3]: df.replace(regex={'\n': '', 'foo': 'xyz'})  # Neither do r'\n' or '\\n' work.
Out[3]:     A   B       C
        0   0   ba\nt   abc
        1   1   xyz     ba\nr
        2   2   bait    xyz

请注意,MMWE改编自replace上的pandas文档,如果df没有转义字符,我可以确认文档中给出的示例可以正常工作。

另外请注意,对this SO question使用正则表达式的答案也不起作用。

预期:

Out[3]:     A   B      C
        0   0   bat    abc
        1   1   xyz    bar
        2   2   bait   xyz

工作:

In [4]: df.replace('\n', '', regex=True).replace('foo', 'xyz')
Out[4]:     A   B      C
        0   0   bat    abc
        1   1   xyz    bar
        2   2   bait   xyz

但是,那当然不是我想要的。我应该将其报告为错误吗?


编辑

奥秘加深:

In [5]: df.replace(regex={'\n': '', r'^fo.$': 'xyz'})
Out[5]:     A   B       C
        0   0   ba\nt   abc
        1   1   xyz     ba\nr
        2   2   bait    xyz

似乎问题只在于转义字符。


编辑

版本信息:

INSTALLED VERSIONS
------------------
commit: None
python: 3.7.1.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 158 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.24.1

0 个答案:

没有答案
相关问题