【问题标题】:How to create a true-for-all index on a pandas dataframe?如何在 pandas 数据框上创建一个真正的索引?
【发布时间】:2022-01-07 13:10:59
【问题描述】:

我正在使用 pandas,并且遇到过一些情况,我有一个以编程方式生成的条件列表,就像这样

conditionals = [
    df['someColumn'] == 'someValue',
    df['someOtherCol'] == 'someOtherValue',
    df['someThirdCol'].isin(['foo','bar','baz']),
   ]

我想选择所有这些条件都为真的行。我想我会做这样的事情。

bigConditional = IHaveNoIdeaOfWhatToPutHere

for conditional in conditionals:
   bigConditional = bigConditional && conditional
filteredDf = df[bigConditional]

我知道我想使用 identity 属性,其中 bigConditional 为我的数据框中的每个索引初始化为一系列 true,这样如果我的条件列表中的任何条件评估为 false,则该行将不在过滤后的数据框,但最初会考虑每一行。

我不知道该怎么做,或者至少不是表明这是故意的最好最简洁的方式

另外,我遇​​到了相反的情况,我只需要一个条件来匹配以将行包含到新数据框中,因此我需要将 bigConditional 设置为 false 为数据框中的每个索引。

【问题讨论】:

    标签: pandas filter


    【解决方案1】:

    也许您可以使用query 并像这样生成您的条件:

    conditionals = [
        "someColumn == 'someValue'",
        "someOtherCol == 'someOtherValue'",
        "someThirdCol.isin(['foo', 'bar', 'baz'])",
    ]
    
    qs = ' & '.join(conditionals)
    
    out = df.query(qs)
    

    或使用eval 创建布尔值而不是过滤您的数据框:

    mask = df.eval(qs)
    

    演示

    假设这个数据框:

    >>> df
         someColumn    someOtherCol  someThirdCol
    0     someValue  someOtherValue           foo
    1     someValue  someOtherValue           baz
    2     someValue    anotherValue  anotherValue
    3  anotherValue    anotherValue  anotherValue
    
    >>> df.query(qs)
      someColumn    someOtherCol someThirdCol
    0  someValue  someOtherValue          foo
    1  someValue  someOtherValue          baz
    
    >>> df.eval(qs)
    0     True
    1     True
    2    False
    3    False
    dtype: bool
    

    您甚至可以使用 f 字符串或其他模板语言将变量传递给您的条件列表。

    【讨论】:

      【解决方案2】:

      如何对条件求和并检查它是否等于条件数

      filteredDf = df.loc[sum(conditionals)==len(conditionals)]
      

      或者更简单,使用np.all

      filteredDf = df.loc[np.all(conditionals, axis=0)]
      

      否则,对于您的原始问题,您可以创建一系列 True 索引,如 df 并且您的 for 循环应该可以工作。

      bigConditional = pd.Series(True, index=df.index)
      

      【讨论】:

        猜你喜欢
        • 2020-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-17
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 2022-10-31
        相关资源
        最近更新 更多