Python netCDF4 - 向现有文件添加一个新变量,形状发生变化

Python netCDF4 - adding a new variable to existing file with change in shape

我有两个 netCDF 文件:file1.ncfile2.nc 唯一的区别是 file1.nc 包含一个变量 'rho' ,我想将其附加到 file2.nc 但通过修改变量。原来的file2.nc里面没有'rho'。 我正在使用 Python 模块 netCDF4。

import netCDF4 as ncd  
file1data=ncd.Dataset('file1.nc')

file1data.variables['rho']

<class 'netCDF4._netCDF4.Variable'> float64 rho(ocean_time, s_rho, eta_rho, xi_rho)
    long_name: density anomaly
    units: kilogram meter-3
    time: ocean_time
    grid: grid
    location: face
    coordinates: lon_rho lat_rho s_rho ocean_time
    field: density, scalar, series
    _FillValue: 1e+37 
unlimited dimensions: ocean_time 
current shape = (2, 15, 1100, 1000) 
filling on

所以 rho 的形状为 [2,15,1100,1000] 但在添加到 file2.nc 时,我只想添加 rho[1,15,1100,1000] 即只有数据第二步。这将导致 'rho' in file2.nc 的形状为 [15,1100,1000]。但我一直做不到。

我一直在尝试这样的代码:

file1data=ncd.Dataset('file1.nc')
rho2=file1data.variables['rho']
file2data=ncd.Dataset('file2.nc','r+') # I also tried with 'w' option; it does not work
file2data.createVariable('rho','float64')
file2data.variables['rho']=rho2  # to copy rho2's attributes
file2data.variables['rho'][:]=rho2[-1,15,1100,1000] # to modify rho's shape in file2.nc
file2data.close()

我在这里错过了什么?

您没有在第二个 netCDF 文件中指定变量 rho 的大小。

你正在做的是:

file2data.createVariable('rho','float64')

虽然它应该是

file2data.createVariable('rho','float64',('ocean_time', 's_rho', 'eta_rho', 'xi_rho'))