Skip to content
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 means

Explanation

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