目錄
1.問題描述:
2.思路:
3.實現(xiàn)過程:
3.1格點位置匹配
3.2寫入表格
4.運行效果
4.1打包站點信息
4.2讀取nc文件列表
4.3提取對應(yīng)格點的nc數(shù)據(jù)
4.4數(shù)據(jù)寫入
1.問題描述:
NCDC的站點數(shù)據(jù)處理在之前三節(jié)里已經(jīng)介紹過了,但是NCDC的就那么幾種數(shù)據(jù)可能不能滿足日常使用,比如說輻射數(shù)據(jù)他就沒有。這時候我們找到其他類型數(shù)據(jù)要和它原有數(shù)據(jù)融合,比如本例找的nc格式數(shù)據(jù)。
2.思路:
本例所用數(shù)據(jù)集是網(wǎng)格化的面尺度數(shù)據(jù),之前處理的NCDC是點數(shù)據(jù),最簡單的處理方法就是把對應(yīng)站點所在經(jīng)緯度找到,再與nc格式數(shù)據(jù)的格點位置匹配,提取對應(yīng)位置的nc數(shù)據(jù),放入表格。
3.實現(xiàn)過程:
3.1格點位置匹配
def matching(lat_value,lon_value,data): # 文件編碼方式[lats,lons],data:需要輸入xr.open_dataset()
'''
經(jīng)緯度與格點位置匹配
輸入經(jīng)緯度,nc數(shù)據(jù)
輸出所在格點位置對應(yīng)索引值 lon_idx:經(jīng)度 lat_idx:緯度
'''
# 獲取經(jīng)度和緯度的坐標(biāo)值
lons = data['lon'].values
lats = data['lat'].values
# 獲取經(jīng)緯度坐標(biāo)的索引值
lat_idx = np.abs(lats - lat_value).argmin()
lon_idx = np.abs(lons - lon_value).argmin()
return lat_idx,lon_idx
上述函數(shù)要求輸入站點所在的經(jīng)度、緯度,以及要讀的nc文件
3.2寫入表格
我直接放完整示例代碼上來,大家按需修改。
# 讀取站點經(jīng)緯度。將對應(yīng)格點數(shù)值寫入dataframe
import xarray as xr
import netCDF4 as nc
import numpy as np
import pandas as pd
import os
import openpyxl
# 定義函數(shù)
def matching(lat_value,lon_value,data): # 文件編碼方式[lats,lons],data:需要輸入xr.open_dataset()
'''
經(jīng)緯度與格點位置匹配
輸入經(jīng)緯度,nc數(shù)據(jù)
輸出所在格點位置對應(yīng)索引值 lon_idx:經(jīng)度 lat_idx:緯度
'''
# 獲取經(jīng)度和緯度的坐標(biāo)值
lons = data['lon'].values
lats = data['lat'].values
# 獲取經(jīng)緯度坐標(biāo)的索引值
lat_idx = np.abs(lats - lat_value).argmin()
lon_idx = np.abs(lons - lon_value).argmin()
return lat_idx,lon_idx
# 輸入站點列表
stations = pd.read_excel('../../Desktop/YellowRiver_station_ID.xlsx') # 站點列表位置,這句按自己需求修改***************
station_code_list = [str(x)[:6] for x in stations["STATION_ID"]] # 沒看懂的復(fù)習(xí)一下 NCDC氣象數(shù)據(jù)的提取與處理(二)
LAT_list = [x for x in stations["LAT"]]
LON_list = [x for x in stations["LON"]]
station_data = zip(station_code_list,LAT_list,LON_list)
station_data = list(station_data) # 包含每個站點的編號、緯度、經(jīng)度,如coordinate[0]為站點編號
# 設(shè)置輸入文件列表
in_rootdir = r"E:\China_station_Srad" # 設(shè)置輸入根目錄, 這句按自己需求修改********************************************
file_list = []
for root, dirs, files in os.walk(in_rootdir): # 獲取輸入根目錄下所有文件
for file in files: # 遍歷所有文件名
if os.path.splitext(file)[-1] == '.nc': # 獲取所有nc文件絕對路徑列表
file_list.append(os.path.join(root, file)) # 拼接出 絕對路徑 并放入列表
# 坐標(biāo)匹配
print("*"*15,"坐標(biāo)匹配","*"*15) # 繪制分割線
data = xr.open_dataset(file_list[0])
coord_idx_list = []
for coordinate in station_data: # coordinate[i],i=0,1,2;依次表示站點編號、緯度、經(jīng)度
coordinate_index = matching(lat_value=coordinate[1],lon_value=coordinate[2],data=data)
coord_idx_list.append((coordinate[0],coordinate_index)) # 形如:[('534630', (258, 418)),…]
print("*"*15,"匹配完成","*"*15) # 繪制分割線
# 讀取nc數(shù)據(jù),寫入xlsx文件
for file_name in file_list:
data = nc.Dataset(file_name)
times = nc.num2date(data["time"][:],data["time"].units) # 時間的格式轉(zhuǎn)換,得到一個數(shù)組
dt = [times[i].strftime() for i in range(data["time"].size)] # 獲取時間序列
# 創(chuàng)建一個新dataframe
df = pd.DataFrame(columns=['Date','srad']) # 這句按自己需求修改***************************************
df['Date'] = pd.to_datetime(dt)
df = df.set_index('Date')
# 設(shè)置輸出路徑
out_rootdir = r"E:\Srad_TEST_2" # 設(shè)置輸出根目錄 ,這句按自己需求修改*****************************************
workbook = openpyxl.Workbook() # 創(chuàng)建Workbook對象
moy = os.path.splitext(file_name)[0][-6:] # 獲取年和月moy:month of year
print("-"*25,moy,"-"*25) # 繪制分割線,年月
outfile_dir = f'{out_rootdir}\\test{moy}.xlsx'
workbook.save(outfile_dir) # 保存空的xlsx文件
for idx in coord_idx_list: # idx[0]表示站點編號、idx[1][0],idx[1][1]分別表示緯度、經(jīng)度
print("*"*15,idx[0],"*"*15) # 繪制分割線,站點代號
location = idx[1] # 獲得格點坐標(biāo)location,包含(緯度,經(jīng)度)
tempfile = []
for i in range(data["time"].size):
tempfile.append(data["srad"][i][location]) # 獲得對應(yīng)格點的屬性值,并存入列表
df["srad"] = tempfile # 對應(yīng)格點的屬性值存入dataframe
srad_mean = df.resample('d').mean() # mean:取屬性值的日均值
writer = pd.ExcelWriter(outfile_dir, engine='openpyxl',mode='a') # 將excel寫入對象writer
"""
將各站點的數(shù)據(jù)表寫入Excel中的
sheet1、sheet2、sheet3……,
sheet以站點編號命名
"""
srad_mean.to_excel(writer, sheet_name=idx[0]) # idx[0]為站點編號
writer.save() # 保存讀寫的內(nèi)容
wb = openpyxl.load_workbook(outfile_dir)
del wb['Sheet'] # 刪除新建Excel時默認(rèn)的空表
wb.save(outfile_dir)
4.運行效果
4.1打包站點信息
首先我有一個xlsx文件,名為“YellowRiver_station_ID.xlsx',之前文章出現(xiàn)過,存放的是NCDC對應(yīng)站點的代號和經(jīng)緯度,(還有高程,這里用不到)形式如下:
?我這邊用了一次 list() 和 zip() 函數(shù)的套用,總之最后打包效果就是[(a1, b1,c1 ),?(a2, b2,c2?), …],abc分別表示站點代號,經(jīng)度,緯度。
4.2讀取nc文件列表
我這邊還有一個文件夾,名為“China_station_Srad”。里面存放著這次要讀的nc文件
?我這里做了一個 file_list ,把文件夾里所有nc格式文件的絕對路徑存進去了
對于每一條絕對路徑,做如下操作
4.3提取對應(yīng)格點的nc數(shù)據(jù)
創(chuàng)建一個dataframe,形式如下:
4.4數(shù)據(jù)寫入
將各站點的數(shù)據(jù)表寫入xlsx中的sheet1、sheet2、sheet3……,sheet以站點編號命名
?最后,?文件名稱以 年月 命名,形如 201812文章來源:http://www.zghlxwxcb.cn/news/detail-755014.html
如有錯漏希望各位大佬不吝指教。文章來源地址http://www.zghlxwxcb.cn/news/detail-755014.html
到了這里,關(guān)于NCDC氣象數(shù)據(jù)的提取與處理(四):python批量讀取、寫入nc數(shù)據(jù)經(jīng)緯度格點數(shù)值的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!