Jeremy
Jeremy

Reputation: 876

Save np.array to netCDF4 files with Python

I am trying to save np.array outputs to netCDF4 format with Python. For example, the 2 dimensions are: longitude = [0,25,50,75], latitude = [0,15,30,45]. The variable is: Data = np.arange(16).reshape(4,4) How can I save them into a netCDF4 file, please? Thanks. The file should be like this when opened by xarray:

<xarray.DataArray 'Data' (lat: 4, lon: 4)>
[16 values with dtype=float32]
Coordinates:
  * lon      (lon) float32 0,25,50,75
  * lat      (lat) float32 0,15,30,45

Upvotes: 3

Views: 3498

Answers (1)

Quai20
Quai20

Reputation: 109

You can simply build the dataarray and save it with xarray to_netcdf() :

df = xr.DataArray(Data, coords=[('lon', longitude), ('lat', latitude)])
df.to_netcdf('filename.nc')

Upvotes: 4

Related Questions