pandas DataFrame过滤器正则表达式

piR*_*red 7 python regex filter pandas

我不明白pandas DataFrame filter.

建立

import pandas as pd

df = pd.DataFrame(
    [
        ['Hello', 'World'],
        ['Just', 'Wanted'],
        ['To', 'Say'],
        ['I\'m', 'Tired']
    ]
)
Run Code Online (Sandbox Code Playgroud)

问题

df.filter([0], regex=r'(Hel|Just)', axis=0)
Run Code Online (Sandbox Code Playgroud)

我希望[0]将第一列指定为要查看的列并axis=0指定过滤行.我得到的是这个:

       0      1
0  Hello  World
Run Code Online (Sandbox Code Playgroud)

我在期待

       0       1
0  Hello   World
1   Just  Wanted
Run Code Online (Sandbox Code Playgroud)

  • 什么会让我得到我所期望的?

unu*_*tbu 11

根据文档,

参数是互斥的,但不会检查

因此,看起来,第一个可选参数,items=[0]胜过第三个可选参数,regex=r'(Hel|Just)'.

In [194]: df.filter([0], regex=r'(Hel|Just)', axis=0)
Out[194]: 
       0      1
0  Hello  World
Run Code Online (Sandbox Code Playgroud)

相当于

In [201]: df.filter([0], axis=0)
Out[201]: 
       0      1
0  Hello  World
Run Code Online (Sandbox Code Playgroud)

这仅仅是[0]沿着0轴选择具有索引值的行.


要获得所需的结果,您可以使用str.contains创建布尔掩码,并用于df.loc选择行:

In [210]: df.loc[df.iloc[:,0].str.contains(r'(Hel|Just)')]
Out[210]: 
       0       1
0  Hello   World
1   Just  Wanted
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 6

这应该工作:

df[df[0].str.contains('(Hel|Just)', regex=True)]