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

如何优雅地为Polars DataFrame指定列添加汇总行?

更优的Polars添加汇总行实现方式

你可以通过直接构造包含所有列的汇总行DataFrame,避免列重排操作,让代码更简洁高效:

import polars as pl

df = pl.DataFrame({
    'name':      ['CHECK', 'CASH', 'BAR', 'SET'],
    'category1': ['AM', 'EU', 'EU', 'AS'],
    'category2': ['CA', 'FR', 'DE', 'CX'],
    'quantity':  [100, -20, 10, -70],
    'exposure':  [11, -3, 2, 8]
})
FLT_COLS   = ['quantity', 'exposure']
OTHER_COLS = [c for c in df.columns if c not in FLT_COLS]

# 直接构造汇总行的所有列
summary_row = pl.DataFrame({
    OTHER_COLS[0]: ['TOTAL'],
    **{col: [''] for col in OTHER_COLS[1:]},
    **{col: [df.select(col).sum().item()] for col in FLT_COLS}
})

result = pl.concat([df, summary_row])
print(result)

优化点说明

  • 避免列重排:原代码中通过[df.columns]重新排列列的操作会产生额外的索引开销,优化后的代码直接按原列顺序构造汇总行,无需额外调整。
  • 代码更简洁:一次性构造所有列的汇总值,逻辑连贯,减少了多次with_columns的调用。
  • 效率提升:减少了中间DataFrame的转换步骤,降低了不必要的内存操作。

原问题代码

import polars as pl

df = pl.DataFrame({
    'name':      ['CHECK', 'CASH', 'BAR', 'SET'],
    'category1': ['AM', 'EU', 'EU', 'AS'],
    'category2': ['CA', 'FR', 'DE', 'CX'],
    'quantity':  [100, -20, 10, -70],
    'exposure':  [11, -3, 2, 8]
})
FLT_COLS   = ['quantity', 'exposure']
OTHER_COLS = [c for c in df.columns if c not in FLT_COLS]

df_temp = df.select(pl.col(FLT_COLS)).sum()\
            .with_columns(pl.lit('TOTAL').alias(OTHER_COLS[0]))\
            .with_columns([pl.lit('').alias(c) for c in OTHER_COLS[1:]])[df.columns]

pl.concat([df, df_temp])

预期输出

shape: (5, 5)
┌───────┬───────────┬───────────┬──────────┬──────────┐
│ name  ┆ category1 ┆ category2 ┆ quantity ┆ exposure │
│ ---   ┆ ---       ┆ ---       ┆ ---      ┆ ---      │
│ str   ┆ str       ┆ str       ┆ i64      ┆ i64      │
╞═══════╪═══════════╪═══════════╪══════════╪══════════╡
│ CHECK ┆ AM        ┆ CA        ┆ 100      ┆ 11       │
│ CASH  ┆ EU        ┆ FR        ┆ -20      ┆ -3       │
│ BAR   ┆ EU        ┆ DE        ┆ 10       ┆ 2        │
│ SET   ┆ AS        ┆ CX        ┆ -70      ┆ 8        │
│ TOTAL ┆           ┆           ┆ 20       ┆ 18       │
└───────┴───────────┴───────────┴──────────┴──────────┘

内容的提问来源于stack exchange,提问作者Phil-ZXX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:32:40