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

Polars透视操作中自定义列名并基于值新增列的实现方法

Polars透视后列名修改与比值列生成实现

步骤1:执行透视并重命名列

先完成透视操作,再将元组格式的列名转换为Long_1、Short_1这类字符串格式:

import polars as pl

# 原DataFrame
df = pl.from_repr("""
┌──────┬────────┬──────────────┬────────────────┬─────────────┬─────┐
│ date ┆ ticker ┆ positionType ┆ predictionType ┆ holdingBars ┆ res │
│ ---  ┆ ---    ┆ ---          ┆ ---            ┆ ---         ┆ --- │
│ str  ┆ str    ┆ str          ┆ str            ┆ i64         ┆ i64 │
╞══════╪════════╪══════════════╪════════════════╪═════════════╪═════╡
│ d1   ┆ t1     ┆ Long         ┆ p1             ┆ 1           ┆ 1   │
│ d1   ┆ t1     ┆ Long         ┆ s1             ┆ 1           ┆ 2   │
│ d1   ┆ t1     ┆ Short        ┆ p1             ┆ 1           ┆ 3   │
│ d1   ┆ t1     ┆ Short        ┆ s1             ┆ 1           ┆ 4   │
│ d1   ┆ t1     ┆ Long         ┆ p1             ┆ 2           ┆ 5   │
│ d1   ┆ t1     ┆ Short        ┆ p1             ┆ 2           ┆ 6   │
└──────┴────────┴──────────────┴────────────────┴─────────────┴─────┘
""")

# 执行透视
df_pivot = df.pivot(
    on=["positionType", "holdingBars"],
    index=["date", "ticker", "predictionType"],      
    values="res"
)

# 重命名列:将元组列名转为"位置_持有周期"格式
df_renamed = df_pivot.rename(
    {col: f"{col[0]}_{col[1]}" for col in df_pivot.columns if isinstance(col, tuple)}
)

步骤2:自动生成比值计算列

从已重命名的列中提取所有唯一的holdingBars值,批量生成Long_N/Short_N格式的比值列:

# 提取所有唯一的持有周期值
bars = {int(col.split("_")[1]) for col in df_renamed.columns if "_" in col}

# 批量添加比值列
for bar in bars:
    df_renamed = df_renamed.with_columns(
        # 若需处理空值,可添加fill_null(0)或其他业务逻辑
        (pl.col(f"Long_{bar}") / pl.col(f"Short_{bar}")).alias(f"Long_{bar}/Short_{bar}")
    )

# 查看最终结果
print(df_renamed)

补充说明

  • 该方法适配多日期、多ticker、多holdingBars的通用场景,无需手动指定每个周期值
  • 若数据中存在某周期下仅包含Long或仅包含Short的情况,除法结果会返回null,可根据需求添加fill_null()处理,例如:
    (pl.col(f"Long_{bar}") / pl.col(f"Short_{bar}")).fill_null(0).alias(f"Long_{bar}/Short_{bar}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:02:20