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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 ...
I said "simply" because when the xarray documentation is well made. If you look in the "Reading and writing files" section (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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.