You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Rust Polars创建指定索引与年月列的透视DataFrame

在Rust中使用Polars创建透视DataFrame(指定索引、按年月聚合)

针对你给出的Python透视表示例,在Rust的Polars中实现同类需求需要先处理日期维度提取,再通过pivot方法完成聚合。以下是完整实现方案:

核心步骤

  • 强类型数据准备:将字符串格式的数值、日期转换为Polars支持的强类型,保证后续聚合逻辑正常运行
  • 年月维度提取:从日期字段中提取年、月并组合为统一格式的字符串,作为透视的列分组依据
  • 透视聚合执行:调用pivot方法,指定索引字段、分组列、聚合字段及聚合函数

完整代码示例

use polars::prelude::*;
use chrono::NaiveDate;

fn main() -> PolarsResult<()> {
    // 构建与Python示例结构一致的初始DataFrame
    let df = DataFrame::new(vec![
        Series::new("obj", &["ring", "shoe", "ring"]),
        // 将字符串价格转换为整数类型
        Series::new("price", &[65, 42, 65]),
        Series::new("value", &[53, 55, 54]),
        // 解析日期字符串为NaiveDate类型
        Series::new(
            "date",
            &[
                NaiveDate::from_ymd_opt(2022, 2, 7).unwrap(),
                NaiveDate::from_ymd_opt(2022, 1, 7).unwrap(),
                NaiveDate::from_ymd_opt(2022, 3, 7).unwrap(),
            ],
        ),
    ])?;

    // 提取年月,生成"YYYY-MM"格式的分组列
    let df_with_year_month = df
        .lazy()
        .with_column(
            col("date")
                .dt()
                .year()
                .cast(DataType::String)
                .str()
                .concat(lit("-"))
                .str()
                .concat(col("date").dt().month().cast(DataType::String).str().pad_start(2, '0'))
                .alias("year_month"),
        )
        .collect()?;

    // 执行透视表操作,对应Python的pivot_table逻辑
    let pivot_df = df_with_year_month
        .pivot(
            vec!["obj"],          // 行分组字段(对应Python的index参数)
            vec!["year_month"],   // 列分组字段(对应Python的columns参数)
            vec!["price", "value"],// 聚合字段(对应Python的values参数)
            |s| s.sum(),          // 聚合函数(对应Python的aggfunc=np.sum)
        )?;

    println!("初始DataFrame:\n{}", df);
    println!("\n透视后的DataFrame:\n{}", pivot_df);

    Ok(())
}

关键细节说明

  1. 类型处理:Rust是强类型语言,必须将示例中的字符串价格转为i32、日期字符串转为NaiveDate,Polars才能正确执行数值聚合和日期操作
  2. 年月格式化:用pad_start(2, '0')保证月份为两位格式(如"02"而非"2"),避免透视列出现格式不一致的问题
  3. 参数对应关系:
    • index参数对应Python示例的index=["obj"],用于定义行分组维度
    • columns参数使用处理后的year_month列,实现按年月维度做列聚合
    • 闭包|s| s.sum()直接对应Python的求和聚合逻辑

内容的提问来源于stack exchange,提问作者Ynax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:20:16