将GeoMet API降水预报数据转换为指定格式的pandas DataFrame
处理方案
前置说明
假设你从GeoMet API获取后整理的嵌套字典结构如下(如果你的结构不同调整遍历逻辑即可):
# 示例输入嵌套字典 precip_forecast = { "2024-06-01": { "00:00": 2.3, "06:00": 5.1, "12:00": 0.0 }, "2024-06-02": { "00:00": 1.2, "12:00": 3.7, "18:00": 0.8 }, "2024-06-03": { "06:00": 4.2, "18:00": 1.5 } }
实现代码
import pandas as pd # 1. 遍历嵌套字典,拆为[日期, UTC时刻, 降水值]三元组列表 data_rows = [] for date, utc_data in precip_forecast.items(): for utc_time, precip_value in utc_data.items(): data_rows.append({ "日期": date, "UTC时刻": utc_time, "降水量": precip_value }) # 2. 生成三列长表 df_long = pd.DataFrame(data_rows) # 3. 透视转换为目标宽表结构,无数据位置自动填充NaN df_target = df_long.pivot( index="日期", columns="UTC时刻", values="降水量" ).reset_index() # 若不需要把日期转为普通列,去掉reset_index()即可
输出示例
处理后得到的df_target结构如下:
| 日期 | 00:00 | 06:00 | 12:00 | 18:00 |
|---|---|---|---|---|
| 2024-06-01 | 2.3 | 5.1 | 0.0 | NaN |
| 2024-06-02 | 1.2 | NaN | 3.7 | 0.8 |
| 2024-06-03 | NaN | 4.2 | NaN | 1.5 |
内容的提问来源于stack exchange,提问作者Chance Gordon
相关产品推荐
相关产品推荐

