'Convert xarray variable to matrix

We open a netcdf4 with xarray, so we have a xarray dataset. Our variable of interest is called SPM, which has 3 dimensions: time, latitude and longitude.

NetCDF4 dataset: drive link

We need to extract the SPM variable as a latitude x longitude matrix.

So far, we have tried the following:

import numpy as np
import xarray as xr
import pandas as pd

image = xr.open_dataset('SPM_ATL_300m_2021-12-15.nc')
df1 = image.to_dataframe().reset_index().set_index(['latitude','longitude'])
array = df1['SPM'].to_numpy()

array.shape

(125060,)

Now, the problem here is that we're getting a 1D array, but we need lat x lon one. Any ideas of how can we do it? Thank you for the help!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source