【问题标题】:Check if Python Polars DataFrame row value exists within a defined list检查定义的列表中是否存在 Python Polars DataFrame 行值
【发布时间】:2022-12-31 13:22:18
【问题描述】:

我真的是 Polars (v0.15.8) 的新手……所以我真的不知道自己在做什么。

我有一个数据框,我想检查列中的每一行是否存在于单独定义的列表中。

例如,这是我的清单:

list_animal = ['cat', 'mouse', 'dog', 'sloth', 'zebra']

这是我的数据框:

df = pl.DataFrame([
        pl.Series('thing', ['cat', 'plant', 'mouse', 'dog', 'sloth', 'zebra', 'shoe']),
        pl.Series('isAnimal', [None, None, None, None, None, None, None]),
])

...看起来像这样:

我希望 df 最终像这样:

我正在努力通过一些示例和 Polars 文档。我找到了两个选择:

  1. 使用 pl.when 函数:
    df = (df.with_column(
         pl.when(
             (pl.col("thing") in list_animal)
         )
         .then(True)
         .otherwise(False)
         .alias("isAnimal2")
    ))
    

    但是,我收到一个错误:

    ValueError: Since Expr are lazy, the truthiness of an Expr is ambiguous. Hint: use '&' or '|' to chain Expr together, not and/or.
    

    要么,

    1. 使用文档here,我尝试按照示例对列表的元素应用表达式。我无法让它工作,但我试过这个:
    chk_if_true = pl.element() in list_animal
    
    df.with_column(
        pl.col("thing").arr.eval(chk_if_true, parallel=True).alias("isAnimal2")
    
    )
    

    ...这给了我这个错误:

    SchemaError: Series of dtype: Utf8 != List
    

    我将不胜感激任何建议;谢谢!

【问题讨论】:

    标签: python dataframe python-polars


    【解决方案1】:

    你在找.is_in()

    >>> df.with_column(pl.col("thing").is_in(list_animal).alias("isAnimal2"))
    shape: (7, 3)
    ┌───────┬──────────┬───────────┐
    │ thing | isAnimal | isAnimal2 │
    │ ---   | ---      | ---       │
    │ str   | f64      | bool      │
    ╞═══════╪══════════╪═══════════╡
    │ cat   | null     | true      │
    ├───────┼──────────┼───────────┤
    │ plant | null     | false     │
    ├───────┼──────────┼───────────┤
    │ mouse | null     | true      │
    ├───────┼──────────┼───────────┤
    │ dog   | null     | true      │
    ├───────┼──────────┼───────────┤
    │ sloth | null     | true      │
    ├───────┼──────────┼───────────┤
    │ zebra | null     | true      │
    ├───────┼──────────┼───────────┤
    │ shoe  | null     | false     │
    └───────┴──────────┴───────────┘
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 2020-04-22
      • 2020-09-07
      • 2015-03-06
      • 2019-02-22
      • 1970-01-01
      • 2021-12-12
      • 2022-06-30
      • 2013-08-07
      相关资源
      最近更新 更多