【问题标题】:pandas DataFrame filter regexpandas DataFrame过滤器正则表达式
【发布时间】:2016-09-02 00:18:49
【问题描述】:

我不明白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

问题

  • 什么能让我达到我的预期?

【问题讨论】:

    标签: python regex pandas filter


    【解决方案1】:

    根据the docs

    参数是互斥的,但不检查

    因此,第一个可选参数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
    

    【讨论】:

      【解决方案2】:

      这应该可行:

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

      【讨论】:

        【解决方案3】:

        这是一个链接方法:

        df.loc[lambda x: x['column_name'].str.contains(regex_patern, regex = True)]
        

        【讨论】:

          猜你喜欢
          • 2016-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-01
          • 1970-01-01
          • 2017-06-19
          相关资源
          最近更新 更多