pandas数据帧筛选器regex

2024-09-23 22:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白pandasDataFramefilter

设置

import pandas as pd

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

问题

df.filter([0], regex=r'(Hel|Just)', axis=0)

我希望[0]指定第一列作为要查看的列,axis=0指定筛选行。我得到的是:

       0      1
0  Hello  World

我在期待

       0       1
0  Hello   World
1   Just  Wanted

问题

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

Tags: toimporthellodataframepandasdfworldas
2条回答

这应该有效:

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

the docs

Arguments are mutually exclusive, but this is not checked for

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

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

相当于

In [201]: df.filter([0], axis=0)
Out[201]: 
       0      1
0  Hello  World

它只是选择索引值在[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

相关问题 更多 >