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

如何使用pandas将参数行数据表转置为按DateTime分组的时间序列表

解决pandas行列转置为时间序列格式问题

核心问题原因

你的原始数据中Value列是字符串类型,直接调用pivot_table的np.mean聚合函数无法对字符串做数值计算,是输出无预期列的主要原因。

正确实现代码

import pandas as pd
import numpy as np

# 读取数据后先做类型转换
df = pd.DataFrame(data=csv, columns = ['DateTime','TagName','Value'])
# 转换Value列为数值格式
df['Value'] = pd.to_numeric(df['Value'])

# 方案1:每个DateTime和TagName组合唯一时,直接用pivot更高效
res = df.pivot(index='DateTime', columns='TagName', values='Value').reset_index()

# 方案2:存在同组合多Value值时,用pivot_table指定聚合规则
res = df.pivot_table(index='DateTime', columns='TagName', values='Value', aggfunc=np.mean).reset_index()

补充说明

  • 如果不需要把DateTime从索引转成普通列,删除代码末尾的.reset_index()即可
  • 聚合规则可根据业务需求调整,例如aggfunc='first'取首次出现的值,aggfunc='sum'求和等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:24:07