【问题标题】:how to code in polars python with the following tidyverse R code?如何使用以下 tidyverse R 代码在 Polars python 中编码?
【发布时间】:2022-11-02 05:47:41
【问题描述】:

我想使用 tidyverse 将我的应用程序从 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))

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

【问题讨论】:

  • 你能添加一个最小的示例数据集和预期的输出吗?
  • 我没有数据集,上面的代码是关于添加名为 no 的列并将 table1 数据帧的行号分配给它,然后将特定行(2,5,7)上的 table1 数据帧的现有列 c 和 d 操作为 0 如果如果不只是取值 c 或 d,则值为 null 或 na,然后操作 table1 数据框的现有列 e 将其分配给另一个 table2 数据框的值,其中键为 table1 a 和 table2 Id,然后操作 table1 数据框的现有列 f 分配给它特定行 3 和 4 上的表 3 的值,表 1 b 和表 3 id 上的键
  • 你将需要比这更努力地工作。为具有正在处理的变量的table1、table2 和table3 制作一些数据。

标签: python r dplyr tidyverse python-polars


【解决方案1】:

我将其他表的分配表示为连接(实际上我也会在 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"] 
)

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 2020-12-09
    • 1970-01-01
    • 2023-04-06
    • 2015-09-09
    • 2012-06-10
    • 2021-03-15
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多