英文:
Export NumPy array as NetCDF4 file
问题
我正在尝试将一个简单的2D NumPy数组导出为.nc
(NetCDF)文件。我尝试按照这个示例进行,但没有成功。
import numpy as np
import netCDF4 as nc
# 数组示例
x = np.random.random((16, 16))
# 创建NetCDF4数据集
with nc.Dataset('data/2d_array.nc', 'w', 'NETCDF4') as ncfile:
ncfile.createDimension('rows', x.shape[0])
ncfile.createDimension('cols', x.shape[1])
data_var = ncfile.createVariable('data', 'int32', ('rows', 'cols'))
data_var = x
然而,当我再次导入数组时,数组中的值都是零:
# 读取文件
with nc.Dataset('data/2d_array.nc', 'r') as ncfile:
array = ncfile.variables['data'][:]
我做错了什么?
英文:
I'm trying to export a simple 2D NumPy array as a .nc
(NetCDF) file. I'm trying to follow this example without exit.
import numpy as np
import netCDF4 as nc
# Array example
x = np.random.random((16,16))
# Create NetCDF4 dataset
with nc.Dataset('data/2d_array.nc', 'w', 'NETCDF4') as ncfile:
ncfile.createDimension('rows', x.shape[0])
ncfile.createDimension('cols', x.shape[1])
data_var = ncfile.createVariable('data', 'int32', ('rows', 'cols'))
data_var = x
However, where I import the array again is all zero:
# Read file
with nc.Dataset('data/2d_array.nc', 'r') as ncfile:
array = ncfile.variables['data'][:]
What I'm doing wrong?
答案1
得分: 3
你正在将data_var
重新绑定到numpy数组,而不是设置您创建的变量的数据。请尝试使用以下方式:
data_var[:] = x
英文:
You're rebinding the data_var
to refer to the numpy array rather than setting the data of the variable you created. Try:
data_var[:] = x
instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论