← Back to NumPy Course | Chapter 6: Math Operations | Lesson 4 of 7

np.sum/min/max

Collapse an array into a single number, or collapse each row or column using the axis argument.

In this page:

  1. np.sum/min/max
Syntax
python
np.sum(arr)
np.min(arr, axis=0)
np.max(arr, axis=1)

np.sum/min/max

sum, min and max reduce an array to one value by default. With axis=0 they work down columns, and axis=1 across rows. argmin and argmax return positions instead of values.

Note: keepdims=True keeps the reduced axis as length 1, which helps broadcasting later.

Example: np.sum/min/max

python
import numpy as np

m = np.array([[3, 1, 4], [1, 5, 9]])
print(m.sum(), m.min(), m.max())
print("column sums:", m.sum(axis=0))
print("row max:", m.max(axis=1))
print("argmax:", m.argmax())

# Output:
# 23 1 9
# column sums: [ 4  6 13]
# row max: [4 9]
# argmax: 5
Related Topics
Common Mistakes
  1. Mixing up axis 0 and axis 1
  2. Using Python's sum on a large array, which is slow
  3. Forgetting argmax returns an index
Chapter Summary
  • Reductions return one value by default
  • axis=0 goes down columns
  • axis=1 goes across rows
  • argmin and argmax return indices
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.