替换netCDF文件中的变量

时间:2018-03-15 20:15:40

标签: python netcdf4

我有一个变量A的netCDF文件具有以下特征:

<class 'netCDF4._netCDF4.Variable'>
float64 Mlail(month, y, x)
units: -
long_name: monthly low veg lai
missing_value: 1.00000002004e+20
unlimited dimensions: 
current shape = (12, 1, 1)
filling off
Mlail = 
[[[ 2.01562]]
[[ 2.00781]]
[[ 2.10156]]
[[ 2.28906]]
[[ 2.80469]]
[[ 3.02344]]
[[ 2.91406]]
[[ 2.77344]]
[[ 2.65625]]
[[ 2.33594]]
[[ 2.14844]]
[[ 2.0625 ]]]

我希望通过以下方式替换这些价值:1,2,3,4,5,6,7,8,9,10,11,12

为此,我尝试了以下命令:

dataset['Mlail'] = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]]

但它没有用,我总是收到返回错误信息:

TypeError: 'netCDF4._netCDF4.Dataset' object does not support item assignment

有谁知道怎么做?

这是我的代码

import netCDF4
dataset = netCDF4.Dataset('surfclim_AmpleroFluxnet.nc')
print (dataset.variables.keys())
import numpy
print ("Mlail = \n", dataset.variables['Mlail'][:])
dataset['Mlail'] = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]] 

1 个答案:

答案 0 :(得分:1)

因此,您的原始代码正在尝试使用值列表替换变量对象。您要做的是替换变量上的值,您可以使用切片([:])替换,就像打印值时一样。您还需要确保打开文件进行修改(使用'a'标志)。所以你的代码将成为:

import netCDF4
import numpy

dataset = netCDF4.Dataset('surfclim_AmpleroFluxnet.nc', 'a')
print (dataset.variables.keys())
print ("Mlail = \n", dataset.variables['Mlail'][:])
var = dataset['Mlail']
var[:] = [[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]]