首页 > 解决方案 > 获取距所选站点最近的网格单元的降水时间序列(全部循环)

问题描述

我对 Python 很陌生,我需要一些帮助。我需要在降水文件 (.nc) 中找到与水流站位置(excel 文件)匹配的网格单元,然后为这些网格单元提取时间序列。

我有一个包含挪威 117 个站点的 Exel 文件,其中包含带有站点名称及其面积、纬度和经度的列。我还有一个 nc 文件,其中包含该站的降水系列。

我设法一次在站上运行 python 脚本(Jupyter notebook),但想为所有站运行它。我该怎么做呢?我知道我需要以某种方式制作一个 for 循环。

这是我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import os
import xarray as xr
import cartopy.crs as ccrs
import cartopy as cy
metapath = "Minestasjoner.xlsx" 
rrdatapath = "cropped_monsum_rr_ens_mean_0.25deg_reg_v20.0e.nc" 
meta = pd.read_excel(metapath)
rrdata = xr.open_dataset(rrdatapath)
i=0
station = meta.iloc[i]["Regime"]*100000 + meta.iloc[i]["Main_nr"]
lon = meta.iloc[i]["Longitude"] #get longitude
lat = meta.iloc[i]["Latitude"] #get latitude
rr_at_obsloc = rrdata["rr"].sel(latitude=lat, longitude=lon, method='nearest') 
df = rr_at_obsloc.to_dataframe() 
print("Station %s with lon=%.2f and lat=%.2f have closest rr gridcell at lon=%.2f and lat=%.2f"%(station,lon,lat,df.longitude[0],df.latitude[0]))
df

标签: pythonexceljupyter-notebook

解决方案


我认为最简单的方法是制作一个dictionary包含该站的站名和降水时间序列的 python,然后将该字典转换为pandas.DataFrame.

以下是你如何在一个简单的循环中做到这一点:

"""
Everything you had previously...
"""

# Initialize empty dictionary to hold station names and time-series
station_name_and_data = {}

# Loop over all stations
for i in range(117):
    # Get name of station 'i'
    station = meta.iloc[i]["Regime"]*100000 + meta.iloc[i]["Main_nr"]

    # Get lat/lon of station 'i'
    lon = meta.iloc[i]["Longitude"] 
    lat = meta.iloc[i]["Latitude"] 

    # Extract precip time-series for this lat-lon
    rr_at_obsloc = rrdata["rr"].sel(latitude=lat, longitude=lon, method='nearest')

    # Put this station name and it's relevant time-series into a dictionary 
    station_name_and_data[station]=rr_at_obsloc

# Finally, convert this dictionary to a pandas dataframe 
df = pd.DataFrame(data=station_name_and_data)

print(df)

推荐阅读