NumPy
Math Operations
Apply element-wise math and reductions.
By EZ4Code Team
mathufuncreductions
Code
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([4, 3, 2, 1])
# Element-wise
print(a + b, a * b, a ** 2, np.sqrt(a))
# Universal functions
print(np.exp(a), np.log(b + 1), np.sin(a))
# Reductions
print(a.sum(), a.mean(), a.std(), a.min(), a.max())
print(np.percentile(a, 90))
# Axis reductions on matrices
m = np.arange(12).reshape(3, 4)
print(m.sum(axis=0)) # column sums
print(m.mean(axis=1)) # row meansExplanation
Arithmetic operators and universal functions like exp, log, and sqrt operate element-wise on arrays. Reductions such as sum, mean, and std collapse an axis; specifying axis=0 collapses rows into per-column results. Operations are vectorized in C, so they run far faster than Python loops.
More NumPy Snippets
Array Creation
Create arrays from lists and built-in constructors.
Indexing and Slicing
Slice arrays and index with boolean masks.
Broadcasting
Combine arrays of compatible shapes without copying.
Linear Algebra
Solve systems, factorize, and compute eigenvalues.
Random Numbers
Sample from distributions with a Generator.
Reshaping
Reshape, transpose, and stack arrays.