3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
這不是python中的解決方案,但是如果您的文件被稱為file_20061105.nc等,您可以從命令行將它們與cdo(氣候數(shù)據(jù)運(yùn)算符)合并,然后使用runmean函數(shù)
cdo mergetime file_*.nc merged_file.nc
cdo runmean,15 merged_file.nc runmean.nc
在某些系統(tǒng)上,您可以打開的文件數(shù)量有限制,在這種情況下,您可能需要先合并文件一年
for year in {2007..2017} ; do
cdo mergetime file_${year}????.nc merged_${year}.nc
done
cdo mergetime merged_????.nc merged_file.nc
cdo runmean,15 merged_file.nc runmean.nc
作為從命令行快速執(zhí)行此操作的另一種方法。
如果你想在python程序中完成這個(gè)任務(wù),那么你可以先用這種方式將文件cat成一個(gè)(或在python中循環(huán)文件并將它們讀入一個(gè)100x360x4000的numpy數(shù)組),然后執(zhí)行運(yùn)行意思是在python中

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
至于我上面的評論:
“每個(gè)文件中有多少項(xiàng)目?...如果每個(gè)文件包含數(shù)千個(gè)網(wǎng)格點(diǎn),我會首先將不同的網(wǎng)格點(diǎn)排序?yàn)閱为?dú)的文件。每個(gè)文件將保存所有日期的相同網(wǎng)格點(diǎn),按以下順序排序日期。這樣就可以輕松加載單個(gè)網(wǎng)格點(diǎn)的整個(gè)文件并計(jì)算其運(yùn)行平均值。”
現(xiàn)在您有一個(gè)用于單個(gè)網(wǎng)格點(diǎn)的文件,我會將數(shù)據(jù)加載到列表中并運(yùn)行這個(gè)簡單的運(yùn)行平均值計(jì)算。(由于您可以訪問整個(gè)數(shù)據(jù)集,您可以使用此代碼。對于在運(yùn)行時(shí)計(jì)算平均值并且沒有結(jié)果歷史記錄的情況,您可以使用此處指定的算法:維基百科 - 移動平均)
#Generate a list of 10 items
my_gridpoints_data=[x for x in range(1, 11)]
print(my_gridpoints_data)
#The average calculation window is set to 3, so the average is for 3 items at a time
avg_window_width: int = 3
avg: float = 0.0
sum: float = 0.0
# Calculate the average of the first 3 items (avg_window_width is 3)
for pos in range(0, avg_window_width):
sum = sum + my_gridpoints_data[pos]
avg = sum / avg_window_width
print(avg)
# Then move the window of the average by subtracting the leftmost item
# and adding a new item from the right
# Do this until the calculation window reaches the list's last item
for pos in range(avg_window_width, my_gridpoints_data.__len__()):
sum = sum + my_gridpoints_data[pos] - my_gridpoints_data[pos - avg_window_width]
avg = sum/avg_window_width
print(avg)
結(jié)果輸出為:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2.0
3.0
4.0
5.0
6.0
7.0
8.0

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
回答有點(diǎn)晚,但對于將來閱讀的人來說,xarray還提供了一個(gè)簡單的 Pythonic 解決方案,非常類似于 @Adrian Tomkins 的答案,其中可以先合并每年的文件,然后由于限制將它們合并到一個(gè)文件中可以在系統(tǒng)中打開的文件數(shù)。
for yr in range(2011,2018):
file_name = str(yr) + 'merge.nc'
xr.open_mfdataset(str(yr)*, combine='nested', concat_dim='time').to_netcdf(file_name)
xr.open_mfdataset(*merge.nc, combine='nested', concat_dim='time').to_netcdf(merge_all.nc)
ds = xr.open_dataset(merge_all.nc, chunks={'lat'=10, 'lon'=10}) # option to chunk if file size is too large, can also be used earlier with open_mfdataset
ds_rolling_mean = ds.rolling(time=15, center=True).mean()
編輯:xarray與其他經(jīng)典工具相比的一大優(yōu)勢是,由于dask. 例如,如果您必須在合并之前對文件進(jìn)行一些預(yù)處理,則將xr.open_mfdataset用戶定義的預(yù)處理函數(shù)作為preprocess參數(shù),并且設(shè)置 'parallel=True' 將在合并之前并行預(yù)處理您的輸入文件。
添加回答
舉報(bào)