【问题标题】:Pandas - filter and regex search the index of DataFramePandas - 过滤和正则表达式搜索 DataFrame 的索引
【发布时间】:2016-06-08 21:08:51
【问题描述】:

我有一个 DataFrame,其中列是 MultiIndex,索引是名称列表,即index=['Andrew', 'Bob', 'Calvin',...]

我想创建一个函数来返回数据帧中所有使用名称“Bob”或以字母“A”开头或以小写字母开头的行。如何做到这一点?

我使用正则表达式参数查看了df.filter(),但它失败了,我得到:

df.filter(regex='a')
TypeError: expected string or buffer

或:

df.filter(regex=('a',1)
TypeError: first argument must be string or compiled pattern

我尝试了其他方法,例如传递 re.compile('a') 无济于事。

【问题讨论】:

标签: python regex pandas


【解决方案1】:

所以看起来我对filter 的部分问题是我使用的是过时的熊猫版本。更新后我不再得到TypeError。在玩了一些之后,看起来我可以使用filter 来满足我的需求。这是我发现的。

只需设置df.filter(regex='string') 将返回与正则表达式匹配的列。这看起来和df.filter(regex='string', axis=1) 一样。

要搜索索引,我只需要df.filter(regex='string', axis=0)

【讨论】:

    【解决方案2】:

    也许通过使用列表理解和 .ix 尝试不同的方法:

    import pandas as pd
    
    df = pd.DataFrame(range(4),index=['Andrew', 'Bob', 'Calvin','yosef'])
    
    df.ix[[x for x in df.index if x=='Bob']]
    
    df.ix[[x for x in df.index if x[0]=='A']]
    
    df.ix[[x for x in df.index if x.islower()]]
    

    【讨论】:

    • 谢谢这回答了我的问题。知道是否有人使用df.filter?很高兴看到一些例子。这很好,但是我需要单独处理搜索列,使我的代码不那么简洁
    猜你喜欢
    • 2015-12-13
    • 2016-09-02
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 2012-03-24
    • 2021-04-30
    相关资源
    最近更新 更多