【问题标题】:select element in a column A while column B does not have a value选择 A 列中的元素,而 B 列没有值
【发布时间】:2021-06-15 13:48:04
【问题描述】:

我想选择 x 中不包含 0 的产品。 输入:

test = pd.DataFrame(
    [
        ['a', 0],
        ['a', 3],
        ['a', 4],
        ['b', 3],
        ['b', 2],
        ['c', 1],
        ['d', 0]
    ]
)

test.columns = ['product', 'x']

test.query("select distinct (product) where x not in (0) ")

预期结果: 乙,丙

如何在 pandas 和 SQL 中做到这一点?

【问题讨论】:

    标签: python sql pandas


    【解决方案1】:

    在 SQL 中,您会使用:

    select product
    from t
    group by product
    having min(x) > 0;
    

    假设x 永远不会是负数,则此方法有效。更一般的表述是:

    having sum(case when x = 0 then 1 else 0 end) = 0
    

    【讨论】:

      【解决方案2】:

      在您的情况下,pandas 可以使用 isin

      test.loc[~test['product'].isin(test.loc[test.x.eq(0),'product']),'product'].unique()
      Out[41]: array(['b', 'c'], dtype=object)
      

      或者使用set

      set(test['product'].tolist())-set(test.loc[test.x.eq(0),'product'].tolist())
      Out[47]: {'b', 'c'}
      

      【讨论】:

        【解决方案3】:

        如果你想过滤你的数据框,你可以使用groupby.any()

        test[~test.groupby('product')['x'].transform(lambda x: x.eq(0).any())]
        

        输出:

        product   x
              b   3
              b   2
              c   1
        

        如果您只想查看唯一值,可以在我上面粘贴的代码末尾添加['product'].unique().tolist()

        然后我们有输出:

        ['b', 'c']
        

        【讨论】:

          猜你喜欢
          • 2022-08-19
          • 2021-02-18
          • 2020-10-13
          • 2012-08-16
          • 1970-01-01
          • 1970-01-01
          • 2011-11-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多