簡體   English   中英

使用 Python 從多個 netcdf 文件創建一個 4D(模型、時間、經度、緯度)netcdf 文件

[英]Create one 4D (model, time, lon, lat) netcdf file from multiple netcdf files using Python

我正在下載 netcdf 格式的氣候數據。 對於每個變量(例如“降水”),我需要合並 9 個 netcdf,每個都屬於一個獨特的氣候 model。 每個 netcdf 具有相同的大小(時間、緯度、經度)。 如何將 9 個 3D netcdfs 合並為一個 4D netcdf? 最終,我想計算每月的累積降水量。 這是我當前的代碼:

variables = ['pr']         
scenarios = ['historical', 'ssp245']        #options ['historical', 'ssp126', 'ssp245', 'ssp370', 'ssp585']
models = ['UKESM1-0-LL', 'MRI-ESM2-0', 'MIROC6', 'MIROC-ES2L', 'IPSL-CM6A-LR',
         'GFDL-ESM4', 'FGOALS-g3', 'CNRM-ESM2-1', 'CanESM5']


save_folder = processing_fn / 'local_climate_assessment' / f'{variable}' / 'output'
if not os.path.exists(save_folder):
    os.makedirs(save_folder)

netcdfs = []

# Create one netcdf per model by merging annual netcdfs
for variable in variables:
    for scenario in scenarios:
        for model in models:
    

            source = processing_fn / 'local_climate_assessment' / f'{variable}' / f'{scenario}' / f'{model}'
            netcdf_fn = save_folder / f'{variable}_{scenario}_{model}.nc'
            
            if not os.path.exists(netcdf_fn):
        
                gdf_model = xr.open_mfdataset(str(source / '*.nc'), combine = 'nested', concat_dim="time", use_cftime=True)
                # rename_dict = {variable, f'{variable}_{scenario}_{model}'}
                # gdf_model.rename(rename_dict, inplace = True)
                gdf_model.to_netcdf(netcdf_fn)
                print(gdf_model.attrs['cmip6_source_id'])
                netcdfs.append(gdf_model)
                
            else:
                gdf_model = xr.open_mfdataset(netcdf_fn)
                netcdfs.append(gdf_model)

# Create one netcdf per variable by merging models
ds = xr.combine_nested(netcdfs, concat_dim = "time")
print(ds)
Out[33]: 
<xarray.Dataset>
Dimensions:  (time: 246095, lat: 47, lon: 50)
Coordinates:
  * time     (time) object 1981-01-01 12:00:00 ... 2060-12-31 12:00:00
  * lat      (lat) float64 31.62 31.88 32.12 32.38 ... 42.38 42.62 42.88 43.12
  * lon      (lon) float64 234.6 234.9 235.1 235.4 ... 246.1 246.4 246.6 246.9
Data variables:
    pr       (time, lat, lon) float32 dask.array<chunksize=(360, 47, 50), meta=np.ndarray>

上面的代碼有效,但我正在創建一個大的 3D netcdf 而不是仍然包含氣候 model 名稱的 4D。 下面的代碼導致以下錯誤:

a = ds.resample(time = 'M').sum()
ValueError: index must be monotonic for resampling

如何創建包含 model 名稱的 4D netcdf,並重新采樣以創建每月總和值?

我絕對推薦閱讀有關組合數據的 xarray 文檔。

combine_nestedconcat_dim參數可以是您想要連接數據的維度列表。 您似乎在連接變量、場景和 model,而不是時間。 因此,在這里消磨時間並提供一維 netCDF 列表正在創建一個重復的時間序列,而沒有關於您的連接維度的信息。

相反,顯式嵌套數據集:

netcdfs = []
for variable in variables:
    netcdfs.append([])
    for scenario in scenarios:
        netcdfs[-1].append([])
        for model in models:
            ... # prep & read in your data
            netcdfs[-1][-1].append(gdf_model)

# use nested lists of datasets and an ordered list
# of coordinates matching the list of datasets
ds = xr.combine_nested(
    netcdfs,
    concat_dim=[
        pd.Index(variables, name="variable"),
        pd.Index(scenarios, name="sceanrio"),
        pd.Index(models, name="model"),
    ],
)

或者,首先擴展每個數據集的維度,然后使用combine_by_coords進行連接:

netcdfs = []
for variable in variables:
    for scenario in scenarios:
        for model in models:
            ... # prep & read in your data
            # add coordinates
            gdf_model = gdf_model.expand_dims(
                variable=[variable],
                scenario=[scenario],
                model=[model],
            )

            netcdfs.append(gdf_model)

# auto-combine using your new coordinates
ds = xr.combine_by_coords(netcdfs)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM