Numpy2 Flashcards
np.add(x, 2)
arithmetic operations are simply convenient wrappers around specific functions built into NumPy
\+ np.add Addition (e.g., 1 + 1 = 2) - np.subtract Subtraction (e.g., 3 - 2 = 1) - np.negative Unary negation (e.g., -2) * np.multiply Multiplication (e.g., 2 * 3 = 6) / np.divide Division (e.g., 3 / 2 = 1.5) // np.floor_divide Floor division (e.g., 3 // 2 = 1) ** np.power Exponentiation (e.g., 2 ** 3 = 8) % np.mod Modulus/remainder (e.g., 9 % 4 = 1)
Simple Numpy Operators
x = np.arange(5)
y = np.empty(5)
np.multiply(x, 10, out=y)
specify the array where the result of the calculation will be stored. Rather than creating a temporary array
y = np.zeros(10)
np.power(2, x, out=y[::2])
used with array views. For example, we can write the results of a computation to every other element of a specified array
[ 1. 0. 2. 0. 4. 0. 8. 0. 16. 0.]
x = np.arange(1, 6)
np.multiply.reduce(x)
if we’d like to reduce an array with a particular operation, we can use the reduce method of any ufunc. A reduce repeatedly applies a given operation to the elements of an array until only a single result remains.
np. add.accumulate(x)
np. multiply.accumulate(x)
store all the intermediate results of the computation, we can instead use accumulate
x = np.arange(1, 6)
np.multiply.outer(x, x)
compute the output of all pairs of two different inputs using the outer method
array([[ 1, 2, 3, 4, 5], [ 2, 4, 6, 8, 10], [ 3, 6, 9, 12, 15], [ 4, 8, 12, 16, 20], [ 5, 10, 15, 20, 25]])
np.min(big_array), np.max(big_array)
find the minimum value and maximum value of any given array
M.sum()
each NumPy aggregation function will return the aggregate over the entire array
M.min(axis=0)
Aggregation functions take an additional argument specifying the axis along which the aggregate is computed. For example, we can find the minimum value within each column by specifying axis=0
np. sum np.nansum Compute sum of elements
np. prod np.nanprod Compute product of elements
np. mean np.nanmean Compute mean of elements
np. std np.nanstd Compute standard deviation
np. var np.nanvar Compute variance
np. min np.nanmin Find minimum value
np. max np.nanmax Find maximum value
np. argmin np.nanargmin Find index of minimum value
np. argmax np.nanargmax Find index of maximum value
np. median np.nanmedian Compute median of elements
np. percentile np.nanpercentile Compute rank-based statistics of elements
Various Aggregation functions
np. any
np. all
N/A Evaluate whether any elements are true
N/A Evaluate whether all elements are true
print(“25th percentile: “, np.percentile(heights, 25))
print(“Median: “, np.median(heights))
print(“75th percentile: “, np.percentile(heights, 75))
the aggregation operation reduced the entire array to a single summarizing value, which gives us information about the distribution of values. We may also wish to compute quantiles