【问题标题】:Filling `null` values of a column with another column用另一列填充一列的“空”值
【发布时间】:2022-11-24 01:09:34
【问题描述】:

我想用 Polars 惰性数据框中同一行的另一列的内容填充列的 null 值。

这在合理的性能下可能吗?

【问题讨论】:

    标签: python python-polars


    【解决方案1】:

    有一个函数:fill_null

    假设我们有这些数据:

    import polars as pl
    
    df = pl.DataFrame({'a': [1, None, 3, 4],
                       'b': [10, 20, 30, 40]
                       }).lazy()
    print(df.collect())
    
    shape: (4, 2)
    ┌──────┬─────┐
    │ a    ┆ b   │
    │ ---  ┆ --- │
    │ i64  ┆ i64 │
    ╞══════╪═════╡
    │ 1    ┆ 10  │
    ├╌╌╌╌╌╌┼╌╌╌╌╌┤
    │ null ┆ 20  │
    ├╌╌╌╌╌╌┼╌╌╌╌╌┤
    │ 3    ┆ 30  │
    ├╌╌╌╌╌╌┼╌╌╌╌╌┤
    │ 4    ┆ 40  │
    └──────┴─────┘
    

    我们可以用 b 列中的值填充 a 列中的空值:

    df.with_column(pl.col('a').fill_null(pl.col('b'))).collect()
    
    shape: (4, 2)
    ┌─────┬─────┐
    │ a   ┆ b   │
    │ --- ┆ --- │
    │ i64 ┆ i64 │
    ╞═════╪═════╡
    │ 1   ┆ 10  │
    ├╌╌╌╌╌┼╌╌╌╌╌┤
    │ 20  ┆ 20  │
    ├╌╌╌╌╌┼╌╌╌╌╌┤
    │ 3   ┆ 30  │
    ├╌╌╌╌╌┼╌╌╌╌╌┤
    │ 4   ┆ 40  │
    └─────┴─────┘
    

    这样的表现会相当不错。

    【讨论】:

      【解决方案2】:

      我刚刚找到了一个可能的解决方案:

      df.with_column(
          pl.when(pl.col("c").is_null())
          .then(pl.col("b"))
          .otherwise(pl.col("a")).alias("a")
      )
      

      【讨论】:

        【解决方案3】:

        df['columnwithnans'].fillna(df["replacingcolumn"], inplace=True)

        【讨论】:

          猜你喜欢
          • 2022-08-18
          • 2022-01-15
          • 1970-01-01
          • 1970-01-01
          • 2021-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-15
          相关资源
          最近更新 更多