【问题标题】:Can you filter pandas dataframe to get all rows that contain specific pattern like I would do for regex你能过滤熊猫数据框来获取所有包含特定模式的行,就像我对正则表达式所做的那样
【发布时间】:2020-01-10 04:36:12
【问题描述】:

我是 python 新手,我正在尝试编写一个管道来捕获在同一行中具有“R”和“yes”的所有 ID。

我有多个包含以下模式的 csv 文件:

CSV文件1

"ID1","R","","","","","yes"
"ID2","S","","","","","yes"

CSVFile2

"ID1","animal","R","","","","","","","","yes"

CSV文件3

"ID1","animal","fish","S","","","","","","","yes"
"ID2","animal","dog","R","","","","","","","yes"

使用正则表达式,我可以用 R 捕获所有行,是的:

input = open(sys.argv[1], 'r')

for line in input:
    if re.match(r'^(?=.*(\bR\b)+)(?=.*(\byes\b)+)', line) is not None:
        print (line)

但是,如果我将其转换为 pandas 数据框,有没有一种方法可以捕获所有具有 R 和 yes 的行,而不必每次都指定该列名,因为并非所有文件都具有相同的列数?

【问题讨论】:

    标签: python regex python-3.x pandas


    【解决方案1】:

    您可以使用布尔索引:

    print(df[df.eq("R").any(1) & df.eq("yes").any(1)])
    

    输出 (CSVFile1)

         0  1   2   3   4   5    6
    0  ID1  R NaN NaN NaN NaN  yes
    

    print(df1[df1.eq("R").any(1) & df1.eq("yes").any(1)])
    

    输出 (CSVFile2)

        0       1    2  3   4   5   6   7   8   9    10
    1  ID2  animal  dog  R NaN NaN NaN NaN NaN NaN  yes
    

    【讨论】:

    • 很方便! any(1) 是什么意思?
    • @cms72 any(axis=1)any(1) 相同,here 是文档
    • 我明白了!谢谢@Chris 和@anky_91!
    猜你喜欢
    • 2016-01-15
    • 2018-01-11
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2015-12-02
    相关资源
    最近更新 更多