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

如何将含嵌套DataFrame的字典列表转换为目标结构的DataFrame?

合并字典列表中的DataFrame并添加年月字段

实现步骤

  1. 遍历每个字典,提取year、month以及对应的weather DataFrame
  2. 为每个weather DataFrame新增year和month列
  3. 合并所有处理后的DataFrame为一个完整的结果

代码示例

import pandas as pd

# 替换成你的实际字典列表
weather_records = [
    {'year': 2010, 'month': 1, 'weather': pd.DataFrame({'temp': [10, 12], 'rainfall': [0, 5]})},
    {'year': 2010, 'month': 2, 'weather': pd.DataFrame({'temp': [15, 17], 'rainfall': [2, 0]})},
    {'year': 2011, 'month': 12, 'weather': pd.DataFrame({'temp': [8, 6], 'rainfall': [10, 3]})}
]

processed_frames = []
for record in weather_records:
    # 复制原DataFrame避免修改原始数据(无需保留原数据可省略copy())
    df = record['weather'].copy()
    # 新增年月字段
    df['year'] = record['year']
    df['month'] = record['month']
    processed_frames.append(df)

# 合并所有DataFrame并重置索引
final_df = pd.concat(processed_frames, ignore_index=True)

# 可选:调整列顺序,把年月放在最前面
column_order = ['year', 'month'] + [col for col in final_df.columns if col not in ['year', 'month']]
final_df = final_df[column_order]

补充说明

  • 若不同weather DataFrame的列名不一致,pd.concat()会自动为缺失列填充NaN
  • ignore_index=True保证合并后的DataFrame索引连续无重复

内容的提问来源于stack exchange,提问作者Nacho Arévalo Evans

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:56:14