NetCDF4 python 创建numpy多维数组
NetCDF4 python create numpy multi-dimension arrays
使用 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
但是这个returns一个TypeError
:
TypeError: an integer is required
我应该如何更改我的输入或编写脚本以获得所需的结果?
您需要一次创建一个维度。例如,将您的尺寸命名为 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']]
使用 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
但是这个returns一个TypeError
:
TypeError: an integer is required
我应该如何更改我的输入或编写脚本以获得所需的结果?
您需要一次创建一个维度。例如,将您的尺寸命名为 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']]