PythonNetCDF4-在形状发生更改的情况下向现有文件添加新变量

PythonNetCDF4-在形状发生更改的情况下向现有文件添加新变量,python,python-3.x,netcdf4,Python,Python 3.x,Netcdf4,我有两个netCDF文件:file1.nc和file2.nc 唯一的区别是file1.nc包含一个变量“rho”,我想通过修改变量将其附加到file2.nc。原始文件2.nc中不包含“rho”。 我正在使用Python模块netCDF4 import netCDF4 as ncd file1data=ncd.Dataset('file1.nc') file1data.variables['rho'] <class 'netCDF4._netCDF4.Variable'> fl

我有两个netCDF文件:
file1.nc
file2.nc
唯一的区别是
file1.nc
包含一个变量“rho”,我想通过修改变量将其附加到
file2.nc
。原始
文件2.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

我错过了什么

您尚未在第二个netCDF文件中指定变量rho的大小

您正在做的是:

file2data.createVariable('rho','float64')
虽然它应该是

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

对不起,我的意思是:所以rho的形状是[2,1511001000],但在添加到file2.nc时,我只想添加rho[1,:,:,:,:],即只添加第二个时间步的数据。第二个文件中的变量和维度是什么?它们与file1相同吗?如果在文件2中有数组形状的
[1511001000]
,则应挤压(使用模块
NumPy
)尺寸,即
将NumPy导入为np;file2data.variables['rho'][:]=np.squence(rho2[-1,1511001000])
file2data.createVariable('rho','float64',('ocean_time', 's_rho', 'eta_rho', 'xi_rho'))