我有兴趣将我使用的一些 Pandas 代码库转换为 Polars。在该代码库中,我们经常使用 Pandas DataFrame,如下所示,其中行代表用户每月的金额:
2023-09-01 2023-10-01 ... 2024-09-01 2024-10-01
customer_id
111111 0.000000 0.000000 ... 918.333333 918.333333
222222 466.666667 883.333333 ... 0.000000 0.000000
333333 0.000000 833.333333 ... 833.333333 0.000000
444444 0.000000 0.000000 ... 833.333333 833.333333
我目前有一个 Polars DataFrame,其中包含类似的信息,只是按行而不是列进行编码:
shape: (313_590, 3)
┌─────────────┬─────────────────────┬────────────┐
│ customer_id ┆ date ┆ amount │
│ --- ┆ --- ┆ --- │
│ i64 ┆ datetime[μs] ┆ f64 │
╞═════════════╪═════════════════════╪════════════╡
│ 111111 ┆ 2023-01-01 00:00:00 ┆ 80.749008 │
│ 222222 ┆ 2023-06-01 00:00:00 ┆ 87.628968 │
│ 333333 ┆ 2023-02-01 00:00:00 ┆ 180.327381 │
│ 333333 ┆ 2022-06-01 00:00:00 ┆ 180.327381 │
│ … ┆ … ┆ … │
│ 555555 ┆ 2022-05-01 00:00:00 ┆ 85.818452 │
│ 666666 ┆ 2022-06-01 00:00:00 ┆ 85.818452 │
│ 777777 ┆ 2023-11-01 00:00:00 ┆ 87.628968 │
│ 888888 ┆ 2023-12-01 00:00:00 ┆ 87.628968 │
└─────────────┴─────────────────────┴────────────┘
在此示例中,客户
111111
可能有 12 行,其中一行代表他们存在的每个月的数据。 Polars 有没有一种方法可以将此 DataFrame 转换为类似于上面的 DataFrame,其中列标签可以只是日期的 ISO 格式字符串?
提前致谢!
.pivot()
来做到这一点
(
df
.sort('date')
.with_columns(pl.col('date').dt.strftime("%Y-%m-%d"))
.pivot('date', index='customer_id')
.with_columns(pl.col(pl.Float64).fill_null(0))
)
shape: (7, 8)
┌────────────┬────────────┬────────────┬───────────┬───────────┬───────────┬───────────┬───────────┐
│ customer_i ┆ 2022-05-01 ┆ 2022-06-01 ┆ 2023-01-0 ┆ 2023-02-0 ┆ 2023-06-0 ┆ 2023-11-0 ┆ 2023-12-0 │
│ d ┆ --- ┆ --- ┆ 1 ┆ 1 ┆ 1 ┆ 1 ┆ 1 │
│ --- ┆ f64 ┆ f64 ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ ┆ ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪════════════╪════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ 555555 ┆ 85.818452 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 │
│ 333333 ┆ 0.0 ┆ 180.327381 ┆ 0.0 ┆ 180.32738 ┆ 0.0 ┆ 0.0 ┆ 0.0 │
│ ┆ ┆ ┆ ┆ 1 ┆ ┆ ┆ │
│ 666666 ┆ 0.0 ┆ 85.818452 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 │
│ 111111 ┆ 0.0 ┆ 0.0 ┆ 80.749008 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 │
│ 222222 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 87.628968 ┆ 0.0 ┆ 0.0 │
│ 777777 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 87.628968 ┆ 0.0 │
│ 888888 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 0.0 ┆ 87.628968 │
└────────────┴────────────┴────────────┴───────────┴───────────┴───────────┴───────────┴───────────┘
需要注意的是,数据透视表对于帮助显示数据非常有用,但如果您需要进行计算,它们通常不是最好的第一步。例如,如果您想要每月跨客户的总和,那么您可能首先需要数据透视表,但最好只在日期上执行 group_by 。