# Making a netcdf data using xarray

I am very very new to the world of data science as I only started using it in my new job so I would really appreciate help from the community experts (maybe also in simple words :)).

I am trying to build a dataset comprising data extracted from a NetCDF data file. The data extract would contain n number of images each of 25x25 size in 17 channels. The idea is to save them as a new data file or object (it could be NetCDF but there is no restriction as long as it is readable by xarray). I am unable to find a way to achieve this because, in xarray, you have N-dimensional data, and to each point in this N-dimensional data there is a label attached. So how do I save 25x25 images with 17 variables (channels) in one dimension (axis of length n, the number of images) so that when I pass the index of the axis (nth image), it returns as dataArray of 17x25x25.

New contributor
Shaz is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• So you want an array of size n that contains subarrays each of size 17x25x25 such that array[x] outputs image[x]? Mar 18 at 11:17
• Hi! Yup. And I would like to have this stored in a NetCDF file (or perhaps another file format would work as well but at the moment I only know how to work with NetCDF). So if you read it, the index 1 should give an image of 17x25x25.
– Shaz
Mar 18 at 13:26

import numpy as np
!pip install netCDF4
!pip install xarray
import netCDF4 as nc
import xarray as xr

image0 = np.array([[[np.zeros(25)+1] for i in range(25)] for i in range(17)]).squeeze()
image1 = np.array([[[np.zeros(25)+2] for i in range(25)] for i in range(17)]).squeeze()
image2 = np.array([[[np.zeros(25)+3] for i in range(25)] for i in range(17)]).squeeze()

# creating some arrays with the same size as the images you asked for

array = np.array([image0, image1, image2])

# numpy array

df = xr.DataArray(array)

# netCDF4 xarray

# df = image, df = image, df = image


Let me know if you meant other.

New contributor
Iya Lee is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.