Export NumPy array as NetCDF4 file

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月27日 20:16:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定