This is an archived version of the course. Please see the latest version of the course.

Indexing functions

Truth value functions

np.all(arr) checks whether all elements in arr are True.

np.any(arr) checks whether at least one element in arr is True.

Note: NaN, positive and negative infinity are considered True because they are non-zero.

print(np.all(np.array([True, True, True])))     ## True
print(np.all(np.array([True, True, False])))    ## False
print(np.any(np.array([True, False, False])))   ## True
print(np.any(np.array([False, False, False])))  ## False

For multidimensional arrays, you can also check across a specific axis.

x = np.array([[True, True, False, False], [True, False, True, False]])
print(np.all(x, axis=0))  ## [ True False False False]
print(np.any(x, axis=0))  ## [ True  True  True False]
print(np.all(x, axis=1))  ## [False False]
print(np.any(x, axis=1))  ## [True True]

Searching functions

np.nonzero() returns the indices of all elements that are not zero (or not False).

x = np.array([[0,2,2], [0,3,0]])
print(np.nonzero(x))    ## (array([0, 0, 1]), array([1, 2, 1]))
print(x[np.nonzero(x)]) ## [2 2 3]

nonzero

Unique

To find a set of unique elements in an array, use (you guessed it!) np.unique().

x = np.array([12, 15, 13, 15, 16, 17, 13, 13, 18, 13, 19, 18, 11, 16, 15])

print(np.unique(x))
## [11 12 13 15 16 17 18 19]

You can also return the index of the first occurrence of each of the unique elements in the array. For example, the number 11 is first encountered at index 12.

(unique_x, unique_indices) = np.unique(x, return_index=True)

print(unique_x)
## [11 12 13 15 16 17 18 19]

print(unique_indices)
## [12  0  2  1  4  5  8 10]

You can also count the number of times each unique element occurs in the array.

(unique_x, unique_counts) = np.unique(x, return_counts=True)

print(unique_x)
## [11 12 13 15 16 17 18 19]

print(unique_counts)
## [1 1 4 3 2 1 2 1]

Sorting functions

You can sort an array using np.sort().

You can also sort across rows or columns by specifying the axis.

a = np.array([3, 1, 2])
print(np.sort(a))  ## [1 2 3]

b = np.array([[6, 4], [1, 0], [2, 7]])

# Sort rows
print(np.sort(b, axis=0)) 
## [[1 0]
##  [2 4]
##  [6 7]]

# Sort columns
print(np.sort(b, axis=1))
## [[4 6]
##  [0 1]
##  [2 7]]

To get the indices after a sort, use np.argsort().

print(np.argsort(a))  ## [1 2 0]

# Get indices of rows after sorting
print(np.argsort(b, axis=0)) 
## [[1 1]
##  [2 0]
##  [0 2]]

# Get indices of columns after sortig
print(np.argsort(b, axis=1))
## [[1 0]
##  [1 0]
##  [0 1]]

Diagonals

If you need to obtain the diagonal of an array, you might find the np.diagonal(arr) function or arr.diagonal() method useful.

x = np.array([[10, 4, 2], [6, 9, 3], [1, 5, 8]])
print(x.diagonal())          ## [10  9  8]
print(x.diagonal(offset=1))  ## [4 3]
print(x.diagonal(offset=-1)) ## [6 5]