如何将含嵌套DataFrame的字典列表转换为目标结构的DataFrame?
合并字典列表中的DataFrame并添加年月字段
实现步骤
- 遍历每个字典,提取
year、month以及对应的weatherDataFrame - 为每个
weatherDataFrame新增year和month列 - 合并所有处理后的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]
补充说明
- 若不同
weatherDataFrame的列名不一致,pd.concat()会自动为缺失列填充NaN ignore_index=True保证合并后的DataFrame索引连续无重复
内容的提问来源于stack exchange,提问作者Nacho Arévalo Evans
相关产品推荐
相关产品推荐

