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

Python遍历文件夹文件填充pandas DataFrame的循环实现问题

气象数据批量整合解决方案

核心问题解决方法

  • Series转字符串:站点ID作为唯一主键的前提下,loc查询返回的单元素Name Series,直接调用.iloc[0]即可取出字符串类型的站点名称,无需手动指定固定索引。
  • 完整循环逻辑:重命名操作仅需执行1次无需放入循环,遍历文件时先提取站点ID、匹配站点名称、读取文件后写入对应列即可,同时增加异常判断避免程序中断。

完整可运行代码

import pandas as pd
import os

# 读取基础表
stations = pd.read_csv('SMHIstationset.csv', index_col='Unnamed: 0')
temperature = pd.read_csv('SMHITemp.csv', index_col='Unnamed: 0')
# 列重命名仅执行一次
temperature.rename(columns={'index':'Timestamp'}, inplace=True)

# 筛选目标文件夹下所有xlsx文件
file_dir = r"C:\Users\SEOP24209\Desktop\API"
xlsx_files = [f for f in os.listdir(file_dir) if f.endswith(".xlsx")]

# 遍历处理每个xlsx文件
for file_name in xlsx_files:
    # 从文件名提取站点ID:请根据你的实际文件名命名规则修改提取逻辑
    # 示例适配规则:文件名为「站点ID_任意字符.xlsx」,如188790_2024气象数据.xlsx
    station_id = int(file_name.split('_')[0])
    
    # 匹配站点名称
    city_series = stations.loc[stations['Id'] == station_id, 'Name']
    # 跳过未匹配到站点的文件
    if city_series.empty:
        print(f"未查询到ID为{station_id}的站点信息,已跳过文件:{file_name}")
        continue
    city_name = city_series.iloc[0]
    
    # 读取当前xlsx的气象数据
    file_full_path = os.path.join(file_dir, file_name)
    df = pd.read_excel(file_full_path)
    
    # 写入温度数据到对应列
    temperature[city_name] = df['T2M']

# 处理完成后可查看结果或导出
print(temperature.head())
# 可选:导出最终整合结果
# temperature.to_csv('整合完成气象温度数据.csv', encoding='utf-8-sig')

注意事项

  • 如果你的xlsx文件命名规则和示例不同,请自行修改station_id的提取逻辑,保证能正确拿到每个文件对应的站点ID即可
  • 若存在单个站点ID对应多条站点记录的情况,可在匹配站点名称时增加去重逻辑,如city_series.drop_duplicates().iloc[0]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:45:08