gpt4 book ai didi

python-3.x - NetCDF4 python创建numpy多维数组

转载 作者:行者123 更新时间:2023-12-05 05:22:11 24 4
gpt4 key购买 nike

我想使用 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: an integer is required

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

最佳答案

您需要一次创建一个维度。例如,调用您的维度 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']]

关于python-3.x - NetCDF4 python创建numpy多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41182563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com