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

如何将API获取的气象站数据解析为DataFrame并保存至PostgreSQL

解析气象站API数据并保存到PostgreSQL

步骤1:数据解析(提取嵌套字段并生成指定表头)

原始数据包含多层嵌套结构,需要先将嵌套字段中的数值和单位提取出来,将表头格式化为「列名(单位)」的形式。

定义单位映射表

先把WMO标准单位转换为易读的中文单位:

unit_mapping = {
    'wmoUnit:Pa': '帕斯卡',
    'wmoUnit:degC': '摄氏度',
    'wmoUnit:m': '米',
    'wmoUnit:percent': '百分比',
    'wmoUnit:mm': '毫米',
    'wmoUnit:km_h-1': '千米/小时',
    'wmoUnit:degree_(angle)': '度(角度)'
}

编写解析逻辑

遍历原始数据,提取需要的字段并整理格式:

def parse_single_weather(item):
    parsed = {}
    # 提取顶层基础字段
    parsed['观测时间'] = item['observation_time']
    parsed['气象站代码'] = item['station']
    
    # 处理weather_results中的嵌套数据
    weather_details = item['weather_results']
    # 定义字段友好名称映射,替换英文驼峰命名
    field_names = {
        'barometricPressure': '气压',
        'dewpoint': '露点温度',
        'heatIndex': '热指数',
        'maxTemperatureLast24Hours': '24小时最高温',
        'minTemperatureLast24Hours': '24小时最低温',
        'precipitationLast3Hours': '3小时降水量',
        'precipitationLast6Hours': '6小时降水量',
        'precipitationLastHour': '1小时降水量',
        'relativeHumidity': '相对湿度',
        'seaLevelPressure': '海平面气压',
        'temperature': '气温',
        'visibility': '能见度',
        'windChill': '风寒指数',
        'windDirection': '风向',
        'windGust': '阵风风速',
        'windSpeed': '风速',
        'elevation': '海拔高度',
        'textDescription': '天气描述',
        'timestamp': '数据时间戳'
    }

    for key, value in weather_details.items():
        # 跳过不需要的字段
        if key in ['@id', '@type', 'presentWeather', 'icon', 'rawMessage', 'station']:
            continue
        
        # 处理带单位的嵌套字段
        if isinstance(value, dict) and 'unitCode' in value:
            unit = unit_mapping.get(value['unitCode'], value['unitCode'])
            col_name = f"{field_names.get(key, key)}({unit})"
            parsed[col_name] = value.get('value')
        else:
            # 处理普通字段
            parsed[field_names.get(key, key)] = value
    
    return parsed

# 批量处理所有数据条目
parsed_list = [parse_single_weather(data_item) for data_item in wea_data]

步骤2:转换为DataFrame

使用Pandas将解析后的数据转为结构化表格:

import pandas as pd

weather_df = pd.DataFrame(parsed_list)

此时DataFrame的表头自动生成为「列名(单位)」格式,例如气压(帕斯卡)、气温(摄氏度),单元格对应数值。

步骤3:保存到PostgreSQL数据库

先安装依赖包:

pip install pandas sqlalchemy psycopg2-binary

然后编写数据库连接和写入逻辑:

from sqlalchemy import create_engine

# 替换为你的数据库实际参数
db_config = {
    'user': '你的用户名',
    'password': '你的密码',
    'host': '数据库地址',
    'port': '5432',
    'db_name': '数据库名称'
}

# 创建数据库连接引擎
engine = create_engine(f"postgresql+psycopg2://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['db_name']}")

# 将DataFrame写入数据库,表名可自定义
# if_exists可选值:'fail'(表存在则报错)、'replace'(覆盖表)、'append'(追加数据)
weather_df.to_sql('weather_station_data', engine, if_exists='append', index=False)

注意事项

  • 对于cloudLayers这类数组字段,可根据需求修改解析逻辑:比如展开为多行数据,或合并为字符串(如CLR(无云))。
  • 确保PostgreSQL实例网络可访问,且账号拥有对应数据库的写入权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:02:15