AtomLearnAtomLearn
DashboardGoalsPathAchievementsReviewSign In
DashboardNumPyArray Operations
NumPyNot Started

Array Operations

Element-wise arithmetic — why NumPy is so much faster than loops

0%
Knowledge0%
Learn & Drill
Fluency0%
Drill & Speed
Retention0%
Mastery & Review
Confidence0%
All modes
Practice

Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.

Upgrade
Knowledge
Fluency
Retention

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

NumPy operations apply to every element at once without a Python loop — this is called vectorization.

python
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

a + b    # [11, 22, 33, 44]  element-wise add
a * b    # [10, 40, 90, 160] element-wise multiply
a ** 2   # [1, 4, 9, 16]     square each element
a + 10   # [11, 12, 13, 14]  scalar broadcast (see next atom)

Aggregate operations:

python a.sum() # 10 a.mean() # 2.5 a.max() # 4 a.min() # 1 a.std() # standard deviation # On 2D arrays, specify axis: m.sum(axis=0) # sum of each column m.sum(axis=1) # sum of each row

Universal functions (ufuncs): np.sqrt, np.log, np.exp, np.abs — all vectorized.

Examples

Row and column sums

axis=0 collapses rows, axis=1 collapses columns

import numpy as np

m = np.array([[1, 2, 3],
              [4, 5, 6]])

print(m.sum())         # 21  (all elements)
print(m.sum(axis=0))   # [5, 7, 9]  (column sums)
print(m.sum(axis=1))   # [6, 15]    (row sums)
print(np.sqrt(m))      # sqrt of every element

How well did you understand this?

Next in NumPy

Broadcasting

Continue