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

生成ReportLab PDF报表前调整Pandas DataFrame列顺序

动态调整Pandas DataFrame列顺序以适配PDF报表需求

需求概述

基于Pandas生成的DataFrame需要调整列顺序,要求:

  • Counterparty 固定为第一列
  • ab cred 始终位于所有普通商品列的最后,且在Cumulative Exposure之前
  • 兼容任意新增的普通商品列(ab cred必存在)
  • 保留Cumulative Exposure及其之后新增的所有列的相对顺序

示例数据

原始DataFrame(out)结构:

Counterparty  ab cred   bar  Cumulative Exposure
0         fizz      0.0  40.0                 40.0
1          foo     10.0  10.0                 20.0

目标列顺序:

Counterparty      bar   ab cred  Cumulative Exposure
0         fizz     40.0  0.0                 40.0
1          foo     10.0  10.0                 20.0

解决方案代码

通过动态拆分、重组列列表实现自适应排序:

# 获取当前所有列的列表
cols = out.columns.tolist()

# 定位Cumulative Exposure的位置,拆分出其及之后的所有列
cumulative_pos = cols.index('Cumulative Exposure')
post_cumulative_cols = cols[cumulative_pos:]

# 筛选出所有普通商品列(排除固定列和汇总/后续列)
regular_commodity_cols = [
    col for col in cols 
    if col not in ['Counterparty', 'ab cred'] + post_cumulative_cols
]

# 按需求重组列顺序
new_col_sequence = ['Counterparty'] + regular_commodity_cols + ['ab cred'] + post_cumulative_cols

# 重新排列DataFrame
out = out[new_col_sequence]

代码说明

  1. 拆分后续列:先找到Cumulative Exposure的位置,提取其及之后的所有列,确保后续新增列的顺序不受影响
  2. 筛选普通商品列:自动排除固定列、ab cred和汇总/后续列,适配任意数量的新增商品列
  3. 重组列顺序:严格按照「固定首列 → 普通商品列 → ab cred → 汇总及后续列」的规则拼接

运行后即可得到符合要求的列顺序,无需手动维护列名列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:10:07