使用python netcdf4库我想为netcdf4读取脚本编写测试数据集。但是,我无法生成所需的输出。
这是我目前的写脚本:
# write file
varlist = ['ABC123', 'DEF456', 'GHI789']
varlist = np.array([[i for i in k] for k in varlist], dtype='S1')
with Dataset(indexfile, 'w', format='NETCDF4') as file:
file.createDimension('vars', [3,6])
vars_list = file.createVariable('vars', 'S1', (u'vars',))
vars_list[:] = varlist
但这会返回TypeError
:
TypeError:需要一个整数
我应该如何更改输入或编写脚本以获得所需的结果?
答案 0 :(得分:1)
您需要一次创建一个维度。例如,调用您的维度x
和y
:
import numpy as np
from netCDF4 import Dataset
indexfile = 'data.nc'
varlist = ['ABC123', 'DEF456', 'GHI789']
varlist = np.array([[i for i in k] for k in varlist], dtype='S1')
with Dataset(indexfile, 'w', format='NETCDF4') as nc_file:
nc_file.createDimension('x', 3)
nc_file.createDimension('y', 6)
vars_list = nc_file.createVariable('vars', 'S1', ('x', 'y'))
vars_list[:] = varlist
生成此文件:
$ ncdump data.nc
netcdf data {
dimensions:
x = 3 ;
y = 6 ;
variables:
char vars(x, y) ;
data:
vars =
"ABC123",
"DEF456",
"GHI789" ;
}
用Python读回来也是如此:
with Dataset(indexfile, 'r', format='NETCDF4') as nc_file:
print(nc_file.variables['vars'][:])
[[b'A' b'B' b'C' b'1' b'2' b'3']
[b'D' b'E' b'F' b'4' b'5' b'6']
[b'G' b'H' b'I' b'7' b'8' b'9']]