Search code examples
arrayslistslicecartopynetcdf4

2D array with Python for cartopy map illustration


Using the code below I read the data from the netCDF file saved locally. The x and y variables are 1D lists of the longitude and latitude elements. The sal_values instead is a masked array; a list of lists see image 1 link.

This is absolutely fine; but I would like to sort the sal_values list in a 2D array in order to plot my data against x and y. When i run e.g sal_values [3][2] i receive the error "index 1 is out of bounds for axis 0 with size 1" which means that sal_values are not an actual 2D array.

import cartopy.crs as ccrs[enter image description here][1]
import matplotlib.pyplot as plt
import numpy as np
import netCDF4



file=r"C:\Users\CFla\Desktop\Ab_sss.nc"
d=netCDF4.Dataset(file)

x=d.variables['lon'][:]
y=d.variables['lat'][:]
sal_values=(d.variables['sss'][:])
sal_values[1][2]


I have found the following line of code which seems to do the trick:

sal_values=(d.variables['sss'][0,:,:]) 

but I would like to understand the slicing method. What does the ',' after ':' do exactly and why if i omit '0' then I receive again the error "index 1 is out of bounds for axis 0 with size 1".

Is there a good source to explain this please. Thanks.


Solution

  • See: https://numpy.org/doc/1.18/reference/arrays.indexing.html

    It seems that d.variables['sss'] is a 3-dimensional array; writing d.variables['sss'][:] gives you the full 3D field, d.variables['sss'][0,:,:] slices the first dimension and returns the full other 2 dimensions, so you end up with a 2D array.

    I'm guessing at this point, but if the dimensions of d.variables['sss'] are e.g. (time, lat, lon), d.variables['sss'][0,:,:] gives you the first time index and the full spatial lat/lon field.