Numpy4 Flashcards
[x[3], x[7], x[2]]
we want to access three different elements
of
[51 92 14 71 60 20 82 86 74 74]
ind = [3, 7, 4]
x[ind]
pass a single list or array of indices to obtain the same result
ind = np.array([[3, 7], [4, 5]]) x[ind] array([[71, 86], [60, 20]])
When using fancy indexing, the shape of the result reflects the shape of the index arrays rather than the shape of the array being indexed
X[row, col]
Like with standard indexing, the first index refers to the row, and the second to the column:
X[1:, [2, 0, 1]]
We can also combine fancy indexing with slicing
x = np.arange(10)
i = np.array([2, 1, 8, 4])
x[i] = 99
print(x)
[ 0 99 99 3 99 5 6 7 99 9]
can also be used to modify parts of an array
x = np.zeros(10)
np.add.at(x, i, 2)
print(x)
The at() method does an in-place application of the given operator at the specified indices (here, i) with the specified value (here, 1). Another method that is similar in spirit is the reduceat() method of ufuncs, which you can read about in the NumPy documentation.
x = np.array([2, 1, 4, 3, 5])
np.sort(x)
return a sorted version of the array without modifying the input
x = np.array([2, 1, 4, 3, 5])
i = np.argsort(x)
print(i)
related function is argsort, which instead returns the indices of the sorted elements
np.sort(X, axis=0)
sort each column of X
np.sort(X, axis=1)
sort each row of X
x = np.array([7, 2, 3, 1, 6, 5, 4])
np.partition(x, 3)
np.partition takes an array and a number K; the result is a new array with the smallest K values to the left of the partition, and the remaining values to the right, in arbitrary order:
np.partition(X, 2, axis=1)
Similarly to sorting, we can partition along an arbitrary axis of a multidimensional array
The result is an array where the first two slots in each row contain the smallest values from that row, with the remaining values filling the remaining slots.
dist_sq = np.sum((X[:, np.newaxis, :] - X[np.newaxis, :, :]) ** 2, axis=-1)
Now we’ll compute the distance between each pair of points. Recall that the squared-distance between two points is the sum of the squared differences in each dimension; using the efficient broadcasting (Computation on Arrays: Broadcasting) and aggregation (Aggregations: Min, Max, and Everything In Between) routines provided by NumPy we can compute the matrix of square distances in a single line of code: