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

如何按type列转换Pandas DataFrame格式?附示例

转换Python DataFrame格式的最优方法

要实现将长格式的空气质量数据转换为目标宽格式,最直接高效的方式是使用pandas的pivot方法,具体步骤如下:

代码实现

假设你的原始DataFrame变量名为df,执行以下代码:

import pandas as pd

# 长表转宽表:按index、date、hour分组,将type列的取值转为新列,tiantan列作为对应值
df_transformed = df.pivot(
    index=['index', 'date', 'hour'],
    columns='type',
    values='tiantan'
)

# 重命名列名以匹配目标格式
df_transformed.columns = ['pm25', 'pm10']

# 重置索引,将分组字段从索引转为普通列
df_transformed = df_transformed.reset_index()

代码说明

  1. pivot是pandas专为长表转宽表场景设计的方法,通过指定分组键(index, date, hour)确保每个时间点对应唯一行;columns='type'将PM2.5和PM10转为独立列;values='tiantan'定义新列的取值来源。
  2. 重命名列名是为了贴合目标格式中的小写命名规范。
  3. reset_index用于将原本作为索引的时间、日期、小时信息转回为普通列,与目标结构完全对齐。

如果你的数据存在同一分组下的重复记录(比如同一时间点同一污染物有多条数据),可以改用pivot_table并指定聚合函数处理:

df_transformed = df.pivot_table(
    index=['index', 'date', 'hour'],
    columns='type',
    values='tiantan',
    aggfunc='mean'  # 可根据需求替换为sum、max等聚合方式
).rename(columns={'PM2.5': 'pm25', 'PM10': 'pm10'}).reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:15:08