Collections in Python
Array

NumPy is a popular library for working with scientific and engineering data. Here, we highlight the array manipulation capabilities offered by NumPy.

A NumPy array is an N-dimensional grid of homogenous values. It can be used to store a single value (scalar), coordinates of a point in N-dimensional space (vector), a 2D matrix containing the linear transformations of a vector (matrix), or even N-dimensional matrices (not tensors though).

>>> import numpy as np >>> a_vector = np.array([1, 2, 3])

>>> print('vector shape:', a_vector.shape)

vector shape: (3,) >>> a_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

>>> print('matrix shape:', a_matrix.shape)

matrix shape: (3, 3)

Now, let us look at some of the frequently used array operations.

Query/Filter/Mask

>>> numbers=np.array([1,2,3,4,5,6,7,8,9,10]) # mask

>>> mask = numbers & 1 == 0

array([False, True, False, True, False, True, False, True, False, True]) # filter out the odds

>>> numbers[mask]

array([ 2, 4, 6, 8, 10]) # zero out the odds and retain the shape

>>> numbers * mask

array([ 0, 2, 0, 4, 0, 6, 0, 8, 0, 10])

Reshape

Reshaping simply rearranges the existing items in an array into a new shape.

# Reshape a row vector to a column vector

>>> row = np.array([1,2,3])

>>> np.reshape(row, (3,1))

array([[1],

[2],

[3]])

>>> np.reshape(row, (-1,1))

array([[1],

[2],

[3]])

Transform

All the power of NumPy comes from its ability to efficiently transform large arrays of data for scientific and engineering computations. This is really a vast topic and we will only touch upon a few key transformations here.

# Vector

>>> row = np.array([1, 2, 3]) # Scale

>>> row*2

array([2, 4, 6]) # Shift

>>> row + np.array([5,5,5])

array([6, 7, 8]) # Rotate by -90 degrees around the z-axis

>>> row = np.array([1, 2, 3])

>>> rotation = np.array([[0, -1, 0],[1, 0, 0],[0, 0, 1]])

>>> np.dot(rotation, row)

array([-2, 1, 3]) # Transpose

>>> rows = np.array([[1,2,3],[2,3,4]])

>>> rows.T

array([[1, 2],

[2, 3],

[3, 4]])

Sort

Sorting is a bit tricky. The Python sort function does not behave the same way as it does for lists.

# Sorting vectors on x-coordinate

>>> rows = np.array([[2, 1, 3],[1, 2, 3]]) # naive sort

>>> np.sort(rows, axis=0)

array([[1, 1, 3],

[2, 2, 3]])

# output does not contain the same vectors at all! # Correct method:

# Obtain the sorted indices for first column (x)

# and then use those indices to sort all the columns >>> ind = np.argsort(rows[:,0],axis=0).reshape(-1,1)

>>> ind = np.repeat(ind, rows.shape[-1],axis=-1)

>>> ind

array([[1, 1, 1],

[0, 0, 0]])

>>> np.take_along_axis(rows,ind,axis=0)

array([[1, 2, 3],

[2, 1, 3]])
['Rajaram Gurumurthi']
['Machine Learning', 'Python', 'Data Science', 'Programming', 'Java']