如何使用以下 tidyverse R 代码在 Polars Python 中进行编码?

Muh*_*kar 1 python r dplyr tidyverse python-polars

我想使用 tidyvers 将我的应用程序从 R 迁移到 Python Polars,这段代码在 python Polars 中的等价物是什么?

new_table <- table1 %>%
  mutate(no = row_number()) %>%
  mutate_at(vars(c, d), ~ifelse(no %in% c(2,5,7), replace_na(., 0), .)) %>%
  mutate(e = table2$value[match(a, table2$id)],
         f = ifelse(no %in% c(3,4), table3$value[match(b, table3$id)], f))
Run Code Online (Sandbox Code Playgroud)

我尝试查看用于组合数据和选择数据的极坐标文档,但仍然不明白

dat*_*.ai 6

我将其他表的分配表示为连接(实际上我也会在 tidyverse 中这样做)。否则翻译是直接的。你需要:

  • with_row_count对于行号
  • with_columns改变列
  • pl.col到参考列
  • pl.when.then.otherwise对于条件表达式
  • fill_nan替换 NaN 值
(table1
    .with_row_count("no", 1)
    .with_columns(
        pl.when(pl.col("no").is_in([2, 5, 7]))
        .then(pl.col(["c", "d"]).fill_nan(0))
        .otherwise(pl.col(["c", "d"]))
    )
    .join(table2, how="left", left_on="a", right_on="id")
    .rename({"value": "e"})
    .join(table3, how="left", left_on="b", right_on="id")
    .with_columns(
        pl.when(pl.col("no").is_in([3, 4]))
        .then(pl.col("value"))
        .otherwise(pl.col("f"))
        .alias("f")
    )
    .select(pl.exclude("value")) # drop the joined column table3["value"] 
)
Run Code Online (Sandbox Code Playgroud)