csdms / ivy

Course material on scientific software development for researchers in earth and planetary surface processes
https://csdms.colorado.edu
Other
75 stars 58 forks source link

Introduce array shape/slicing with simple rectangular example #110

Closed mdpiper closed 1 year ago

mdpiper commented 1 year ago

In the Python lessons, we should introduce nD array shape--what are rows and what are columns, and how to index them--with simple rectangular examples that can be printed and viewed in tabular form.

mdpiper commented 1 year ago

Shapes and slicing in nD arrays

Some sample code from a notebook I made in class.

import numpy as np

n_rows = 4
n_cols = 5

a = np.arange(n_rows*n_cols)
a

b = a.reshape(n_rows, n_cols)
b

b.shape

# What are the values in the first column?
b[:,0]

# What are the values in the first row?
b[0,:]

What about 3D arrays?

nx = 4
ny = 3
nz = 2

c = np.arange(nx*ny*nz)
c

d = c.reshape(nz, ny, nx)
d

d.shape

# Slice the array to show the first *z* level.
d[0, :, :]