Array Manipulation Routines

NoteQuestion

I have an array. What can I do with it?

TipAnswer

NumPy offers many array manipulation routines, which can be grouped around the following families:

  • Basic operations
  • Changing array shape
  • Transpose-like operations
  • Changing number of dimensions
  • Changing kind of array
  • Joining arrays
  • Splitting arrays
  • Tiling arrays
  • Adding and removing elements
  • Rearranging elements

Presenting every NumPy array manipulation routine would require writing a dedicated book (and certainly falls beyond the remit of an introductory module on Python). That said, let me whet the reader’s appetite by illustrating a sample of miscellaneous routines (see the code snippet below). Here is the sequence of tasks we accomplish: first, we create an array of shape (6,) (see line 5); then, we change the shape of the array (line 10) and transpose its rows and columns (line 16); in the lower section of the snippet we join two arrays using several routines: .concatenate joins two arrays along the desired axis (the default axis is the first one, meaning the second arrays are concatenated row-wise); .vstack requires to pass a tuple of arrays to stack row-wise; .hstack requires to pass a tuple of arrays to stack column-wise. It is worth noticing that the rules for vector/matrix manipulation we learned at school apply to the routines that join arrays. In other words, two NumPy arrays can be joined if and only have the same length on the joining axis. For example, it is possible to stack vertically two arrays with the shape (3, 3) and (2, 3) because they have the same number of columns.

# import numpy with the socially accepted alias 'np'
>>> import numpy as np

# the array
>>> A = np.arange(6)
>>> A
array([0, 1, 2, 3, 4, 5])

# reshape the array into a 2x3 array
>>> A = A.reshape(2, 3)
>>> A
array([[0, 1, 2],
       [3, 4, 5]])

# transpose the array
>>> A.T
array([[0, 3],
       [1, 4],
       [2, 5]])

# get back to a 'flat' array with shape (6,)
>>> A.ravel()
array([0, 1, 2, 3, 4, 5])

# reshape the array into a 3x2 array
>>> A.reshape(3, 2)
array([[0, 1],
       [2, 3],
       [4, 5]])

# join two arrays --- note the dimensions for the concatenation must match
>>> np.concatenate((A.reshape(3, 2), A.T))
array([[0, 1],
       [2, 3],
       [4, 5],
       [0, 3],
       [1, 4],
       [2, 5]])

# stack two arrays vertically (ROW-WISE)
>>> np.vstack((A, np.array([6, 7, 8])))

# stack two arrays horizontally (COLUMN-WISE)
>>> np.hstack((A, np.array([6, 7]).reshape(2, 1)))
array([[0, 1, 2, 6],
       [3, 4, 5, 7]])