2

使用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:需要一个整数

我应该如何更改输入或编写脚本以获得所需的结果?

4

1 回答 1

2

您需要一次创建一个维度。例如,调用您的尺寸xy

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']]
于 2016-12-16T16:15:41.787 回答