替换netcdf变量并重写为新的netcdf文件



有谁能帮我解决以下问题吗?我有一个netcdf文件,具有以下维度和变量:尺寸:y(100), n2(2), x(100),变量(维度):int64 valid_time(), int64 start_time(), float64 y(y), float64 y_bounds(y,n2), float64 x(x), float64 x_bounds(x,n2), int16 precipitation(y,x), int8 proj()

netcdf包含一个用于降水的2d数组(100,100)。现在我有一个新的相同大小的2d数组(100,100)与不同的值。我想知道如何将netcdf中的数组替换为新的数组,并将其重写为新的netcdf。我尝试了下面的代码,但它不能取代数组(它可以重写和重命名文件。Nc到newfile。Nc(不替换数组)

import xarray as xr
ds=xr.open_dataset('file.nc')
precip=ds.variables['precipitation']
precip=np.array(precip)
precip=new_array
ds.to_netcdf('newfile.nc')

首先提供您的new_array作为一个2D numpy数组,您可以做:

import numpy as np
new_array = np.array(new_array)

那么你可以试试:

import xarray as xr
ds=xr.open_dataset('file.nc')
ds.variables['precipitation'].values = new_array
ds.to_netcdf('newfile.nc)

import xarray as xr
ds=xr.open_dataset('file.nc')
ds['precipitation'].values = new_array
ds.to_netcdf('newfile.nc)

但是要注意,x和y维度以及你的new_array映射到网格中心的方式应该与你的precipitation一致。