{:check ["true"]}
import numpy as np
#
# Suppose we have a ndarray
#
data = np.random.rand(10, 4)
data
#
# Sort each row by sorting along the column axis.
# The default sorting axis is the last axis (axis=-1)
#
np.sort(data)
#
# Sort each column by sorting along the row axis
#
np.sort(data, axis=0)
numpy.argsort
returns the indices of the original ndarray in sorted order.
np.argsort(data)
numpy.argsort
is best used to sort a single axis ndarray. Suppose we want to sort by the first column of data, and still
keep the rows intact.
#
# This is the first column
#
data[:, 0]
#
# We can sort it, but keep the indice positions
#
sorted_idx = np.argsort(data[:, 0])
sorted_idx
#
# Now, we can use `sorted_idx` to rearrange data
#
data[sorted_idx, :]
#
# Let's do reverse sorting. This can be done by sorting
# `-data` instead of `data`.
#
rev_sorted_idx = np.argsort(-data[:, 0])
rev_sorted_idx
#
# Rearrange the rows of data according to reversely sorted first column
#
data[rev_sorted_idx,:]
Check out numpy.lexsort
which acts like numpy.argsort
by performs comparison over multiple columns. This is known as lexicographical sorting.
In linear algebra, we are primarily interested in matrices (ndarrays with 2 axes) and vectors (ndarrays with one axis).
#
# Matrix multiplication
#
M = np.arange(12).reshape(3,4)
M
N = np.random.rand(2, 3)
N
#
# We can multiple N x M, but not M X N.
#
np.dot(N, M)
np.dot(M, N)
#
# Matrix multiplication has a very convenient shorthand in Python.
#
# Use the `@` operator.
#
N @ M
M @ N
v = np.random.rand(4)
v
M @ v
N @ v
Dot product between two vectors of the same length is defined as:
$$ u\cdot v = \sum_i u_i\times v_i$$u = np.random.rand(4)
u
np.dot(u, v)
u @ v
#
# Don't forget that we can always perform element-wise multiplication of ndarrays of the same dimension
#
u * v