python - 获取距所选站点最近的网格单元的降水时间序列(全部循环)
问题描述
我对 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
解决方案
我认为最简单的方法是制作一个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)
推荐阅读
- android - 在 Xamarin Android 的运行时向用户请求位置权限时应用程序崩溃
- ios - 在 iOS 的 Firebase 测试实验室中测试无密码身份验证
- android-studio - 为什么 Android Studio 会为某些类输入完整路径?
- java - Spring Batch 从外部类停止作业执行
- python - Wy 函数 time.time() 不会附加到 pandas 数据帧
- html - 如何使整个 div 成为 mailto 链接?
- graph-databases - 为什么大多数图形数据库不支持双向边?
- google-apps-script - 谷歌表自动递增 ID/主键
- google-cloud-dataflow - 谷歌云数据流:连续 8 次测量 GC 抖动后关闭 JVM
- amazon-dynamodb - 无服务器 dynamodb 启用连续备份