【发布时间】:2019-06-08 23:03:34
【问题描述】:
我有两个 netCDF 文件:file1.nc 和 file2.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] 即仅第二个时间步的数据。这将导致 file2.nc 中的“rho”的形状为 [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()
我在这里缺少什么?
【问题讨论】:
-
对不起,我的意思是:所以 rho 的形状为 [2,15,1100,1000] 但在添加到 file2.nc 时,我只想添加 rho[1, :, :, :] 即只有第二个时间步的数据。
-
第二个文件中的变量和维度是什么?它们与file1相同吗?如果在 file2 中,您有数组形状
[15,1100,1000],您应该挤压(使用模块NumPy)尺寸,即import numpy as np;file2data.variables['rho'][:]=np.squeeze(rho2[-1,15,1100,1000])
标签: python python-3.x netcdf4