
import numpy as np
np.random.seed(0) # seed for reproducibility
x1 = np.random.randint(10, size=6) # One-dimensional array
x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional arrayndim (the number of dimensions), shape (the size of each dimension), and size (the total size of the array):
print("x3 ndim: ", x3.ndim)
print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)dtype, the data type of the array (which we discussed previously in Understanding Data Types in Python):
print("dtype:", x3.dtype)itemsize, which lists the size (in bytes) of each array element, and nbytes, which lists the total size (in bytes) of the array:
print("itemsize:", x3.itemsize, "bytes")
print("nbytes:", x3.nbytes, "bytes")nbytes is equal to itemsize times size.
x1
x1[0]
x1[4]
x1[-1]
x1[-2]
x2
x2[0, 0]
x2[2, 0]
x2[2, -1]
x2[0, 0] = 12
x2
x1[0] = 3.14159 # this will be truncated!
x1:) character.
The NumPy slicing syntax follows that of the standard Python list; to access a slice of an array x, use this:x[start:stop:step]start=0, stop=size of dimension, step=1.
We'll take a look at accessing sub-arrays in one dimension and in multiple dimensions.
x = np.arange(10)
x
x[:5] # first five elements
x[5:] # elements after index 5
x[4:7] # middle sub-array
x[::2] # every other element
x[1::2] # every other element, starting at index 1step value is negative.
In this case, the defaults for start and stop are swapped.
This becomes a convenient way to reverse an array:
x[::-1] # all elements, reversed
x[5::-2] # reversed every other from index 5
x2