3.2. Array Computation#

Hide code cell source

import sys
from pathlib import Path

current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent  # ← Add project root, not chapters
        break
else:
    project_root = Path.cwd().parent.parent

sys.path.insert(0, str(project_root))

from shared import thinkpython, diagram, jupyturtle

NumPy organizes array operations along axes, masks, and broadcasting rules. Fig. 3.5 summarizes how these concepts interact when reducing or slicing arrays (Harris et al., 2020).

NumPy array concepts

Fig. 3.5 NumPy Array Concepts #

NumPy is so important in the Pythonic data science world because it optimizes computation with arrays. Computational efficiency on NumPy arrays lies in the use of vectorized operations, or vector-based operations, generally implemented through NumPy’s universal array functions (ufuncs), that work on entire arrays at once rather than looping through individual elements. This approach is dramatically faster than traditional Python loops and is fundamental to efficient data science.

This section explores how NumPy’s universal functions (ufuncs) enable fast, efficient computation on arrays. You’ll learn why vectorization matters, how to use ufuncs effectively, and advanced techniques like broadcasting and boolean indexing.

What You’ll Learn

  1. Vectorized vs. Iterative Operations: Compare performance and see why vectorization matters

  2. Universal Functions (ufuncs): Explore unary and binary operations for arrays

  3. Array Arithmetic: Perform mathematical operations on arrays

  4. Aggregation: Compute summary statistics efficiently

  5. Advanced Features: Broadcasting, indexing, and boolean logic

3.2.1. Iterative vs Vectorized Operations#

Vectorized operations in NumPy refer to performing operations on entire arrays at once, rather than iterating through individual elements using Python loops.

Vectorized operations are more efficient, and this section compares NumPy’s vectorized operations with Python list iteration.

3.2.1.1. Contender 1: A Python Loop#

The first contender is a function that uses a Python for loop (an iterative loop) to visit one element at a time. The code is a computing example, not a business case:

import numpy as np

Create some test values with a NumPy random number generator (Random Number Generation explains generators and seeds):

rng = np.random.default_rng(seed=42)      ### a random number generator; seed 42 makes the values repeatable

The function below computes the reciprocal (1 divided by the value) of each element, one element per pass through the loop:

def compute_reciprocals_iteration(values):
    output = np.empty(len(values))          ### an array to fill; its starting values are arbitrary
    for i in range(len(values)):            ### visit one element at a time
        output[i] = 1.0 / values[i]
    return output                           ### return the output array
### test the function with a small array of values
values = rng.integers(1, 10, size=5)        ### 5 integers from 1 to 9 (10 is excluded)
print(values)
compute_reciprocals_iteration(values)
[1 7 6 4 4]
array([1.        , 0.14285714, 0.16666667, 0.25      , 0.25      ])

3.2.1.2. Contender 2: Vectorized Operation (NO LOOP!)#

def compute_reciprocals_numpy(values):
    return 1.0 / values             ### no loop!
### test the function with the same array of values
compute_reciprocals_numpy(values)   ### compare with compute_reciprocals_iteration(values)
array([1.        , 0.14285714, 0.16666667, 0.25      , 0.25      ])

3.2.1.2.1. Who Wins?#

Now time both functions on an array of 1,000,000 values. %timeit runs a line many times and reports the average time per run:

big_array = 1000000
values = rng.integers(1, 100, size=big_array)

%timeit compute_reciprocals_iteration(values)
%timeit compute_reciprocals_numpy(values)
1.62 s ± 15.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
690 μs ± 1.61 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

Note

  • ms (millisecond) is 1/1000 second

  • μs (microsecond) is one millionth (1/1,000,000) of a second (10⁻⁶ s)

  • ns (nanosecond) is one billionth of a second (10⁻⁹ s)

The vectorized version is far faster than the Python loop, even though both work on the same NumPy array. Why?

  • The loop runs one Python step per element, and Python checks each value’s type on every step.

  • The vectorized version hands the whole array to NumPy’s compiled code, which loops over raw numbers stored side by side in memory.

3.2.1.2.2. Round 2: sum()#

You have seen how much faster vectorized operations are than a Python loop. Now compare Python’s built-in sum() on a list with NumPy’s np.sum() on an array. (The following sample code is adapted from geeksforgeeks )

import time

#################### list sum() ####################
lst = list(range(1000000))                     ### create list
start_time = time.perf_counter()               ### time starts
iterative_sum = sum(lst)                       ### sum list
iterative_time = time.perf_counter() - start_time

#################### numpy sum() ####################
arr = np.arange(1000000)                       ### create array
start_time = time.perf_counter()
vectorized_sum = np.sum(arr)                   ### sum array
vectorized_time = time.perf_counter() - start_time

print("List sum: ", iterative_sum, "in", iterative_time, "seconds")
print("NumPy sum:", vectorized_sum, "in", vectorized_time, "seconds")
print(f"NumPy array sum is {iterative_time / vectorized_time:.2f} times faster than list sum.")
List sum:  499999500000 in 0.007798934999982521 seconds
NumPy sum: 499999500000 in 0.00030773699998576376 seconds
NumPy array sum is 25.34 times faster than list sum.

3.2.2. Universal Functions#

A universal function (ufunc) is a NumPy function that works element by element on whole arrays: it computes the entire array (‘vector’) at once, without a Python loop over individual elements. Ufuncs run as compiled code, which is where their speed comes from.

As a simple example, suppose you want to add the elements of two lists pair by pair. With Python lists, you would use:

  • a for loop

  • the zip() function

  • the append() method

x = list(range(1, 5)) 
y = list(range(5, 9))
z = []

for i, j in zip(x, y):
  z.append(i + j)

print(z)
[6, 8, 10, 12]

With NumPy arrays, the + operator adds the two arrays element-wise in one step, and it runs a ufunc (np.add()) behind the scenes:

x = np.arange(1, 5) 
y = np.arange(5, 9)

z = x + y

print(z)              
[ 6  8 10 12]

3.2.2.1. Array Arithmetic#

NumPy implements each arithmetic operator with a ufunc, as shown in the table below. You can call the ufunc by name, such as np.add(a, b), or use Python’s arithmetic operator, such as a + b, which is usually easier to read. Either way, the looping happens in NumPy’s compiled layer, so it runs much faster than a Python loop.

Arithmetic ufunc implementation:

Operation

Operator

ufunc (NumPy)

Example

Vectorized Meaning

Addition

+

np.add

a + b

Element-wise addition

Subtraction

-

np.subtract

a - b

Element-wise subtraction

Multiplication

*

np.multiply

a * b

Element-wise multiply (not matrix multiply)

Division

/

np.true_divide (np.divide)

a / b

Element-wise division

Floor Division

//

np.floor_divide

a // b

Element-wise floor (quotient rounded down)

Modulo

%

np.mod (np.remainder)

a % b

Element-wise remainder

Power

**

np.power

a ** 2

Element-wise power (e.g., square each element)

Examples of using the NumPy arithmetic ufuncs are as follows, and you may use the Python arithmetic operators in place of ufuncs for these vectorized operations, as listed above.

### arithmetic operators with a scalar (a single number)

x = np.arange(5)
print("x ==", x)
print("x + 5  ==", x + 5)
print("x - 5  ==", x - 5)
print("x * 2  ==", x * 2)
print("x / 2  ==", x / 2)
print("x // 2 ==", x // 2) # floor division
x == [0 1 2 3 4]
x + 5  == [5 6 7 8 9]
x - 5  == [-5 -4 -3 -2 -1]
x * 2  == [0 2 4 6 8]
x / 2  == [0.  0.5 1.  1.5 2. ]
x // 2 == [0 0 1 1 2]

The same operators work between two arrays of the same shape. For example, np.add(arr1, arr2) is the same as arr1 + arr2:

arr1 = np.arange(5)
arr2 = np.arange(5, 10)

print(np.add(arr1, arr2))     ### ufunc
print(arr1 + arr2)            ### ufunc honors Python arithmetic operators
[ 5  7  9 11 13]
[ 5  7  9 11 13]

Now one example for each of the arithmetic ufuncs:

arr1 = np.arange(5)                  ### 0...4
arr2 = np.arange(5, 10)              ### 5...9

print(np.add(arr1, arr2))            ### arr1 + arr2
print(np.subtract(arr1, arr2))       ### arr1 - arr2
print(np.negative(arr1))             ### -arr1
print(np.multiply(arr1, arr2))       ### arr1 * arr2
print(np.divide(arr1, arr2))         ### arr1 / arr2
print(np.floor_divide(arr1, 3))      ### arr1 // 3
print(np.ceil(np.divide(arr1, 2)))   ### arr1 / 2, rounded up to a whole number
print(np.power(arr1, 3))             ### arr1 ** 3
print(np.mod(arr1, 2))               ### arr1 % 2
[ 5  7  9 11 13]
[-5 -5 -5 -5 -5]
[ 0 -1 -2 -3 -4]
[ 0  6 14 24 36]
[0.         0.16666667 0.28571429 0.375      0.44444444]
[0 0 0 1 1]
[0. 1. 1. 2. 2.]
[ 0  1  8 27 64]
[0 1 0 1 0]

3.2.2.2. Division by Zero#

Unlike regular Python, you do not receive an error when you divide a number by zero (ZeroDivisionError: division by zero). Instead,

  • inf: You receive a inf and a RuntimeWarning: divide by zero encountered in divide.

  • nan: You receive a nan and a RuntimeWarning: invalid value encountered in divide.

In NumPy, np.nan represents “Not a Number,” a special floating-point value defined by the IEEE 754 standard. It signifies missing or undefined numerical data, such as the result of an indeterminate mathematical operation (e.g., dividing zero by zero). So,

Expression

Result

Why

5 / 0

inf

Overflow toward infinity

0 / 0

nan

Indeterminate form

arr1 = np.arange(5)
arr2 = np.arange(5)

print(arr1[0] / arr2[0])
print(arr1 / arr2)
nan
[nan  1.  1.  1.  1.]
/tmp/ipykernel_2522/1681753110.py:4: RuntimeWarning: invalid value encountered in scalar divide
  print(arr1[0] / arr2[0])
/tmp/ipykernel_2522/1681753110.py:5: RuntimeWarning: invalid value encountered in divide
  print(arr1 / arr2)
arr1 = np.arange(5)
arr2 = np.arange(5, 10)

print(arr2[0] / arr1[0])
print(arr2 / arr1)
inf
[       inf 6.         3.5        2.66666667 2.25      ]
/tmp/ipykernel_2522/1933371002.py:4: RuntimeWarning: divide by zero encountered in scalar divide
  print(arr2[0] / arr1[0])
/tmp/ipykernel_2522/1933371002.py:5: RuntimeWarning: divide by zero encountered in divide
  print(arr2 / arr1)

3.2.2.3. More math ufuncs#

NumPy comes with many mathematical ufuncs that work on every element of an array, for example:

  • np.abs(): absolute value

  • np.sqrt(): square root

  • np.exp(): e raised to each value

  • np.log(): natural logarithm

  • np.sin(): sine (in radians)

For abs(), start with Python abs().

%%expect TypeError

y = [-2, -1, 0, 1, 2]
abs(y)
TypeError: bad operand type for abs(): 'list'

Now, with NumPy, as long as it is a NumPy array, ufunc works as expected.

x = np.array([-2, -1, 0, 1, 2])

print(abs(x))
print(np.absolute(x))     ### ufunc
print(np.abs(x))          ### alias to ufunc
[2 1 0 1 2]
[2 1 0 1 2]
[2 1 0 1 2]

For sqrt(),

### make a 2-D array using reshape() method
arr = np.arange(12)
arr = arr.reshape(3, 4)
arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
### taking square roots
np.sqrt(arr)
array([[0.        , 1.        , 1.41421356, 1.73205081],
       [2.        , 2.23606798, 2.44948974, 2.64575131],
       [2.82842712, 3.        , 3.16227766, 3.31662479]])

For exp(), log(), and sin():

x = np.array([1, 2, 3])

print(np.exp(x))      ### e raised to each value
print(np.log(x))      ### natural logarithm of each value
print(np.sin(x))      ### sine of each value, in radians
[ 2.71828183  7.3890561  20.08553692]
[0.         0.69314718 1.09861229]
[0.84147098 0.90929743 0.14112001]

3.2.3. Aggregations#

NumPy aggregation functions allow you to summarize many values into fewer, often a single value. Instead of looping through an array manually, functions like np.sum(), np.mean(), np.min(), and np.max() efficiently compute totals, averages, and other summary statistics. These operations are vectorized and run as compiled code, making them much faster than pure Python loops. When working with multi-dimensional arrays, you can also use the axis parameter to control the direction of the aggregation.

Aggregation = “Reduce many values into fewer values.”

Function

What It Computes

Example

Axis Support

Notes

np.sum()

Total sum

np.sum(a)

Yes

Adds all elements

np.mean()

Average

np.mean(a)

Yes

Arithmetic mean

np.median()

Median

np.median(a)

Yes

Middle value

np.min()

Minimum

np.min(a)

Yes

Smallest value

np.max()

Maximum

np.max(a)

Yes

Largest value

np.std()

Standard deviation

np.std(a)

Yes

Spread (default population)

np.var()

Variance

np.var(a)

Yes

Spread squared

np.prod()

Product

np.prod(a)

Yes

Multiply all elements

np.argmin()

Index of min

np.argmin(a)

Yes

Position of smallest value

np.argmax()

Index of max

np.argmax(a)

Yes

Position of largest value

np.any()

Any True?

np.any(a)

Yes

Logical OR across elements

np.all()

All True?

np.all(a)

Yes

Logical AND across elements

3.2.3.1. Axis Support#

Most aggregation functions take an axis= parameter. The axis you specify is the one that gets collapsed:

  • axis=0 → remove row dimension → result keeps columns

  • axis=1 → remove column dimension → result keeps rows

arr = np.arange(1, 7).reshape(2, 3)
arr
array([[1, 2, 3],
       [4, 5, 6]])

Call

Result

Meaning

np.sum(arr)

21

Sum of all elements

np.sum(arr, axis=0)

[5 7 9]

Column sums

np.sum(arr, axis=1)

[6 15]

Row sums

total = np.sum(arr)             ### all elements
ax_0 = np.sum(arr, axis=0)      ### collapse the rows: one sum per column
ax_1 = np.sum(arr, axis=1)      ### collapse the columns: one sum per row

print(total)
print(ax_0)
print(ax_1)
21
[5 7 9]
[ 6 15]

3.2.3.2. sum()#

There are three ways to sum a 1-D NumPy array:

  • Python’s built-in sum() function

  • NumPy’s np.sum() function

  • the array’s sum() method

arr = np.arange(10)
print(arr)

print(sum(arr))       ### Python's built-in sum() works on any iterable
print(np.sum(arr))    ### NumPy's sum() function takes the array as an argument
print(arr.sum())      ### the array's sum() method does the same as np.sum()
[0 1 2 3 4 5 6 7 8 9]
45
45
45

With 1,000 random decimals, the two sums can differ in the last few digits. Python’s sum() adds the values one at a time, while np.sum() adds them in pairs. Decimal numbers are stored with limited precision, so each order of adding rounds slightly differently. For example:

>>> 0.0001 + 0.0002
0.00030000000000000003
rng = np.random.default_rng(seed=42)
rnd_arr = rng.random(1000)          ### 1,000 random decimals in [0, 1)
print(rnd_arr[:5])                  ### the first five values
print()

print(f"Python sum: {sum(rnd_arr)}")
print(f"NumPy  sum: {np.sum(rnd_arr)}")
[0.77395605 0.43887844 0.85859792 0.69736803 0.09417735]

Python sum: 497.17783852843127
NumPy  sum: 497.17783852843195

Considering performance, NumPy’s compiled code version of the operation is computed much more quickly.

big_array = rng.random(1000000)

%timeit sum(big_array)
%timeit np.sum(big_array)
78.5 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
200 μs ± 129 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

3.2.3.3. min() and max()#

Python has built-in min and max functions, and NumPy has corresponding functions for finding the minimum and maximum values of an array.

rng = np.random.default_rng(seed=42)    ### create random number generator (rng)

big_array = rng.random(1000000)         ### use the rng to generate random numbers

Python min/max:

min(big_array), max(big_array)          ### two values separated by a comma display as a tuple
(np.float64(1.2500323287589765e-07), np.float64(0.9999997172035572))

NumPy min/max:

np.min(big_array), np.max(big_array)
(np.float64(1.2500323287589765e-07), np.float64(0.9999997172035572))

There is a different syntax, though, which uses the methods of the array objects:

big_array.min(), big_array.max()
(np.float64(1.2500323287589765e-07), np.float64(0.9999997172035572))

Compare performance:

%timeit min(big_array)
%timeit np.min(big_array)
%timeit big_array.min()
47.8 ms ± 742 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
145 μs ± 2.04 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
137 μs ± 638 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

On NumPy arrays, use NumPy’s functions and methods, such as np.min() and arr.min(), rather than Python’s built-in min(), max(), and sum(): they give the same answer much faster.

3.2.3.4. argmin() and argmax()#

argmin() and argmax() return the position (index) of the smallest and largest values rather than the values themselves. They tell you where an extreme value is, such as the month with the highest sales.

arr_1d = np.array([1, 2, 10, 4])
arr_2d = np.array([[1, 2, 3],
                   [4, 20, 6]])

print(arr_1d.argmax())   ### 2: the largest value, 10, is at index 2
print(arr_1d.argmin())   ### 0: the smallest value, 1, is at index 0
2
0

For a 2-D array, argmax() and argmin() without axis count positions as if the array were flattened into one row, read row by row. In arr_2d, the largest value, 20, is the fifth value, so its position is 4. np.unravel_index() turns that position back into a row and a column, and axis= gives one position per column (axis=0) or per row (axis=1).

print(arr_2d.argmax())                ### 4: a position in the flattened array

row, col = np.unravel_index(arr_2d.argmax(), arr_2d.shape)
print(row, col)                       ### 1 1: row 1, column 1

print(arr_2d.argmax(axis=0))          ### for each column, the row of its largest value
print(arr_2d.argmax(axis=1))          ### for each row, the column of its largest value
4
1 1
[1 1 1]
[2 1]

3.2.4. Broadcasting#

Broadcasting lets NumPy combine arrays of different shapes without copying data: the smaller array is conceptually ‘stretched’ to match, computed on the fly rather than materialized in memory. Arithmetic broadcasting (like x + 100) returns a new array and leaves the original unchanged; but broadcasting during in-place assignment (like arr[0:5] = 10) does modify the original array.

### same shape addition: default behavior

x = np.arange(0, 5)     ### 0, 1, 2, 3, 4
y = np.arange(5, 10)    ### 5, 6, 7, 8, 9
x + y
array([ 5,  7,  9, 11, 13])

3.2.4.1. Broadcasting Rules#

NumPy compares the two shapes dimension by dimension, starting from the last one and moving left:

  • Two dimensions are compatible if they are equal or if one of them is 1.

  • A missing dimension counts as 1, so an array of shape (3,) works like shape (1, 3).

  • A dimension of size 1 is “stretched” to match the other array. If any pair of dimensions is neither equal nor 1, NumPy raises a ValueError.

Simple broadcasting: value 100 below is stretched or broadcasted into the array [0, 1, 2, 3, 4] and the results are added.

### different shape: add a scalar to a 1-D array
### broadcasting

x + 100
array([100, 101, 102, 103, 104])
### x stays the same
x
array([0, 1, 2, 3, 4])
### a (2, 3) array plus a (3,) array

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

b = np.array([10, 20, 30])

print(a + b)     ### b is added to each row of a
[[11 22 33]
 [14 25 36]]

Here, b has shape (3,). NumPy treats it as shape (1, 3) and stretches it to (2, 3), so the same b is added to each row of a.

### setting a value with index range 

arr = np.arange(0, 10)
arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
### assign one value to a slice: 10 is broadcast to all five positions,
### and the original array changes

arr[0:5] = 10

### show array again:
arr
array([10, 10, 10, 10, 10,  5,  6,  7,  8,  9])
### Exercise: Basic Broadcasting with Scalar
### Weekly sales for four products are stored in a NumPy array.
### Apply a 10% discount to all sales values and print the result.
sales = np.array([100, 150, 200, 120])
### Your code starts here:



### Your code ends here.

Hide code cell source

### Solution
sales = np.array([100, 150, 200, 120])
discounted_sales = sales * 0.90     ### 0.90 is broadcast to every element
print(discounted_sales)
[ 90. 135. 180. 108.]

3.2.5. Masking#

NumPy masking selects, changes, or counts array elements based on a condition. Instead of using indices, you create a boolean mask (an array of True/False values) that marks which elements to keep, change, or analyze. You build masks with:

  • Comparison operators

  • Logical operators

arr = np.array([1, 2, 3, 4, 5, 6])   ### create array

### Create a mask (boolean array)
mask = arr > 3             ### Result: [False, False, False, True, True, True]
print(mask)

### Apply the mask to select elements
result = arr[mask]         # Result: [4, 5, 6]
print(result)
[False False False  True  True  True]
[4 5 6]

3.2.5.1. Comparison operators#

Each comparison operator (>, <, >=, <=, !=, ==) compares every element and returns a boolean array:

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

print(x > 3)
print(x < 3)
print(x >= 3)
print(x <= 3)
print(x != 3)     ### not equal
print(x == 3)     ### equal
[False False False  True  True]
[ True  True False False False]
[False False  True  True  True]
[ True  True  True False False]
[ True  True False  True  True]
[False False  True False False]

Each operator also has a ufunc name, such as np.greater() for > and np.equal() for ==:

print(np.greater(x, 3))   ### same as x > 3
print(np.equal(x, 3))     ### same as x == 3
[False False False  True  True]
[False False  True False False]

3.2.5.2. Logical operations#

Logical operations combine masks: & (and), | (or), and ~ (not), with each comparison in parentheses. Python’s and and or test an object as a whole, so they raise an error on an array with more than one element; &, |, and ~ work element by element.

a = np.array([1, 5, 10, 15])
print((a > 3) & (a < 12))       ### True where 3 < value < 12
print((a < 3) | (a > 12))       ### True where value < 3 or value > 12
print(~(a > 5))                 ### ~ (not) flips each True and False
[False  True  True False]
[ True False False  True]
[ True  True False False]
a = np.array([1, 5, 10, 15]).reshape(2, 2)
print(a)
print()

print((a > 3) & (a < 12))       ### True where 3 < value < 12
print()
print((a < 3) | (a > 12))       ### True where value < 3 or value > 12
print()
print(~(a > 5))                 ### ~ (not) flips each True and False
[[ 1  5]
 [10 15]]

[[False  True]
 [ True False]]

[[ True False]
 [False  True]]

[[ True  True]
 [False False]]

3.2.5.2.1. Logical ufuncs#

The same operations are available as ufuncs, which work on boolean arrays:

arr1 = np.array([True, False, True, False])
arr2 = np.array([True, True, False, False])

print(f"logical_and: {np.logical_and(arr1, arr2)}")
print(f"logical_or:  {np.logical_or(arr1, arr2)}")
print(f"logical_not: {np.logical_not(arr1)}")
print(f"logical_xor: {np.logical_xor(arr1, arr2)}")     ### XOR (exclusive or): True when the two inputs differ
logical_and: [ True False False False]
logical_or:  [ True  True  True False]
logical_not: [False  True False  True]
logical_xor: [False  True  True False]

3.2.5.3. Filtering Values#

A mask inside square brackets keeps only the elements where the mask is True:

temperatures = np.array([68, 72, 95, 58, 88, 102])

hot_days = temperatures[temperatures > 85]  ### [95, 88, 102]
hot_days
array([ 95,  88, 102])

3.2.5.4. Modifying elements#

Assigning a value to a masked selection changes only the selected elements, in the original array:

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

arr[arr > 3] = 0               ### Sets elements > 3 to 0
arr
array([1, 2, 3, 0, 0])

3.2.5.5. Counting elements#

True counts as 1 and False as 0, so summing a mask counts the elements that meet the condition:

arr = np.array([5, 10, 15, 20, 25])

count = np.sum(arr > 12)  ### counts elements > 12 (3 of them)
print(count)
3

3.2.6. Fancy Indexing#

Fancy indexing uses an array or list of indices to select several elements, or entire rows, at once and in any order.

arr = np.array([10, 20, 30, 40, 50, 60, 70])
indices = np.array([0, 3, 5])    ### indices to select: 0th, 3rd, and 5th elements

selected_elements = arr[indices]
print(selected_elements)         ### Output: [10 40 60]
[10 40 60]
arr_2d = np.arange(12).reshape(3, 4)     ### the 2-D array
print("Original 2D array:\n", arr_2d)

print()

### indexing
row_indices = np.array([0, 1, 2])
col_indices = np.array([1, 3, 0])

### Select elements at (0, 1), (1, 3), and (2, 0)
selected_elements = arr_2d[row_indices, col_indices]     ### pay attention to the syntax here
print("Selected elements:", selected_elements)           ### selected elements: [ 1  7  8]
Original 2D array:
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Selected elements: [1 7 8]

Another example of fancy indexing uses a 10x10 matrix in which every value in row i is i. Broadcasting builds it without a loop: adding a column of row numbers, shape (10, 1), to a (10, 10) array of zeros stretches the column across all ten columns.

### a (10, 10) array of zeros plus a (10, 1) column of row numbers
arr2d = np.zeros((10, 10)) + np.arange(10).reshape(10, 1)
arr2d
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
       [3., 3., 3., 3., 3., 3., 3., 3., 3., 3.],
       [4., 4., 4., 4., 4., 4., 4., 4., 4., 4.],
       [5., 5., 5., 5., 5., 5., 5., 5., 5., 5.],
       [6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
       [7., 7., 7., 7., 7., 7., 7., 7., 7., 7.],
       [8., 8., 8., 8., 8., 8., 8., 8., 8., 8.],
       [9., 9., 9., 9., 9., 9., 9., 9., 9., 9.]])

Now do fancy indexing with a list of indices — you can select rows in any order you want, and they’ll be returned in that exact order:

  1. The double brackets [[ ]] mean “use a list of indices.”

  2. [2,4,6,8] specifies which rows to select: row 2, row 4, row 6, row 8.

  3. Result: A new 4×10 array with those 4 rows stacked together in that order

### allows in any order
arr2d[[2,4,6,8]]
array([[2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
       [4., 4., 4., 4., 4., 4., 4., 4., 4., 4.],
       [6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
       [8., 8., 8., 8., 8., 8., 8., 8., 8., 8.]])

Now, another fancy indexing:

  1. Same idea, but notice the rows are in a different order: 6, 4, 2, 7.

  2. NumPy doesn’t care about the order — it just grabs the rows in the sequence you specify.

  3. Result: Row 6, then row 4, then row 2, then row 7 (in that exact sequence).

### allows in any order
arr2d[[6,4,2,7]]
array([[6., 6., 6., 6., 6., 6., 6., 6., 6., 6.],
       [4., 4., 4., 4., 4., 4., 4., 4., 4., 4.],
       [2., 2., 2., 2., 2., 2., 2., 2., 2., 2.],
       [7., 7., 7., 7., 7., 7., 7., 7., 7., 7.]])

3.2.7. Sorting Arrays#

3.2.7.1. Sorting lists#

  • Python sorted( ) function; returns a copy of sorted Python list

  • Python list sort( ) method (work on the object, change in place)

### sorted function on a list

lst = [3, 1, 4, 1, 5, 9, 2, 6]

sorted(lst)      ### returns a sorted copy
[1, 1, 2, 3, 4, 5, 6, 9]
lst              ### original object unchanged
[3, 1, 4, 1, 5, 9, 2, 6]
### list.sort method: sort in place

lst.sort()       ### no return value, sorts "in place"
lst              ### object changed
[1, 1, 2, 3, 4, 5, 6, 9]
### sorting a string 

state = 'MISSOURI' 
sorted(state)
['I', 'I', 'M', 'O', 'R', 'S', 'S', 'U']
state            ### original object not changed
'MISSOURI'
### sorted() on an array returns a Python list, not an array
### surprise!

arr = np.array([3, 1, 4, 1, 5, 9, 2, 6])
print("Original array:", arr, type(arr))

sorted_arr = sorted(arr)
print("Sorted array:", sorted_arr, type(sorted_arr))    ### a list
Original array: [3 1 4 1 5 9 2 6] <class 'numpy.ndarray'>
Sorted array: [np.int64(1), np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5), np.int64(6), np.int64(9)] <class 'list'>

3.2.7.2. Sorting NumPy arrays#

  • np.sort(): Both np.sort() and Python sorted( ) functions return a sorted copy of an array; original object unchanged.

  • argsort(): returns the indices that would sort the array.

  • arr.sort(): the array method sorts the array in place, like a list’s sort() method.

arr = np.array([1, 5, 4, 2, 3])
### python sorted( ) function

sorted(arr)
[np.int64(1), np.int64(2), np.int64(3), np.int64(4), np.int64(5)]
### arr unchanged

arr
array([1, 5, 4, 2, 3])
### np.sort() returns a sorted copy

np.sort(arr)
array([1, 2, 3, 4, 5])
arr              ### original object not changed
array([1, 5, 4, 2, 3])

argsort returns the indices of the sorted elements:

np.argsort(arr)
array([0, 3, 4, 2, 1])

The first index, 0, points to the smallest value, arr[0] (1); the last index, 1, points to the largest value, arr[1] (5).

Finally, the array method sort() changes the array itself:

arr.sort()       ### sorts in place, returns nothing
arr              ### object changed
array([1, 2, 3, 4, 5])

3.2.8. Quick Reference: Array Computation#

The examples below summarize array computation tools used in this section.

Math and aggregations
x + y                # same as np.add(x, y)
np.sqrt(x); np.abs(x)
np.sum(m); m.sum()
np.mean(m)
np.min(m); np.max(m)
np.argmin(x); np.argmax(x)
np.sum(m, axis=0)    # one result per column
np.sum(m, axis=1)    # one result per row
Broadcasting, masks, and indexing
# prefer vectorized operations over loops
x + 100              # broadcasting
x[x > 3]             # filter with a mask
x[x > 3] = 0         # change selected values
np.sum(x > 3)        # count matches
(x > 3) & (x < 10)   # combine masks
x[[0, 3, 5]]         # fancy indexing
Sorting
sorted(lst)          # returns sorted copy
lst.sort()           # sorts in place
np.sort(arr)         # returns sorted copy
arr.sort()           # sorts in place
np.argsort(arr)      # returns sorted indices