【问题标题】:How to filter dataframe in pandas by 'str' in columns name?如何通过列名中的“str”过滤熊猫中的数据框?
【发布时间】:2015-02-24 18:27:41
【问题描述】:

关注this recipe。我试图通过包含字符串“+”的列名过滤数据框。示例如下:

B = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
                columns=['A', '+B', '+C'], index=[1, 2, 3, 4, 5])

所以我想要一个数据框 C,其中只有“+B”和“+C”列。

C = B.filter(regex='+')

但是我得到了错误:

File "c:\users\hernan\anaconda\lib\site-packages\pandas\core\generic.py", line 1888, in filter
matcher = re.compile(regex)
File "c:\users\hernan\anaconda\lib\re.py", line 190, in compile
return _compile(pattern, flags)
File "c:\users\hernan\anaconda\lib\re.py", line 244, in _compile
raise error, v # invalid expression
error: nothing to repeat

配方说它是 Python 3。我使用 python 2.7。不过,我认为这不是问题所在。

埃尔南

【问题讨论】:

    标签: python-2.7 pandas filter dataframe


    【解决方案1】:

    + 在正则表达式中有特殊含义(参见here)。您可以使用\ 转义它:

    >>> C = B.filter(regex='\+')
    >>> C
       +B  +C
    1   5   2
    2   4   4
    3   3   1
    4   2   2
    5   1   4
    

    或者,由于您只关心+ 的存在,您可以改用like 参数:

    >>> C = B.filter(like="+")
    >>> C
       +B  +C
    1   5   2
    2   4   4
    3   3   1
    4   2   2
    5   1   4
    

    【讨论】:

    • 谢谢!。相关,是否可以做类似 C = B.filter(like="+" or like="-") 的事情?
    • @hernanavella:不能使用like,但您可以使用regex,类似于B.filter(regex="\+|-")(其中| 表示“或”)。但坦率地说,那时我不会费心去装聪明,我会写B[[col for col in B if "+" in col or "-" in col]]
    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2018-07-13
    • 2022-01-04
    • 1970-01-01
    • 2016-08-02
    相关资源
    最近更新 更多