1

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?

sermomon
  • 254
  • 1
  • 11

1 Answers1

3

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.

Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • If you're having trouble getting your head around the difference, check out https://youtu.be/_AEJHKGk9ns or https://nedbatchelder.com/text/names.html for text version – Sam Mason Jun 27 '23 at 23:06