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?
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.