3

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

Jeremy
  • 849
  • 6
  • 15

1 Answers1

4

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')

Quai20
  • 109
  • 6
  • Thanks. It is not simple without you! Excuse me, do you know how to define the variable name? I got this when opening the file: ````Data variables: __xarray_dataarray_variable__ (lon, lat) float64 ...```` – Jeremy Jan 14 '20 at 13:25
  • I said "simply" because when the xarray documentation is well made. If you look in the "Reading and writing files" section (http://xarray.pydata.org/en/stable/io.html), you get clear examples. For your variable name, you can define df.name before saving it to netcdf. – Quai20 Jan 14 '20 at 13:44