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

基于Pandas实现SQL表数据快速重组的性能优化问询

高性能重塑时序DataFrame:长表转宽表优化

数据结构与需求

原始DataFrame结构(从MySQL获取)

Time    QuantityMeasured       Value
0       t1          A                       7
1       t1          B                       2
2       t1          C                       8
3       t1          D                       9
4       t1          E                       5
...     ...         ...                     ...
18482   tn          A                       5
18483   tn          C                       3
18484   tn          E                       4
18485   tn          B                       5
18486   tn          D                       1

目标格式

需转换为以下列表/NumPy数组格式:

list_of_time = ['t1', ..., 'tn']
list_of_A    = [7, ..., 5]
list_of_B    = [2, ..., 5]
list_of_C    = [8, ..., 3]
list_of_D    = [9, ..., 8]

约束条件

  • 无法修改数据库存储结构
  • 仅需保留测量量A-D,每个时间戳包含3-4个无关测量量
  • 各时间戳下的测量量顺序不固定

当前实现与性能问题

  1. 初始方案:循环构建字典列表再拆分到各列表,性能极差
  2. 优化后方案:使用pivot方法
pivot_df = data.pivot(index='Time', columns='QuantityMeasured', values='Value')
time = pivot_df.index.tolist()
A = pivot_df['A'].tolist()
B = pivot_df['B'].tolist()
C = pivot_df['C'].tolist()
D = pivot_df['D'].tolist()
  • 平均耗时:0.18-0.22秒,仅比循环方案快约0.03秒
  • 性能期望:将耗时降低一个数量级(如0.02秒内完成18.5k条数据转换),至少提升2倍

疑问

  • 该场景下是否存在性能上限?
  • 有没有更优的实现方案?
  • 上述性能期望是否合理?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:23:34