Skip to main content
Editor

NumPy Operations: Element-wise Math, Aggregations, and ufuncs

Intermediate25 min6 exercises90 XP
0/6 exercises

You know how to create NumPy arrays. Now it's time to actually do things with them. The real power of NumPy is that you can perform math on entire arrays at once - no loops required.

In this tutorial, you'll learn element-wise arithmetic, aggregation functions like sum and mean, the axis parameter for row/column operations, universal functions (ufuncs), and boolean and fancy indexing to filter data.

What Are Element-wise Operations?

When you use arithmetic operators on NumPy arrays, the operation applies to every element independently. Add two arrays and each pair of corresponding elements gets added. Multiply by a number and every element gets multiplied.

elementwise.py
import numpy as np
a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])
print(a + b) # [11 22 33 44]
print(a - b) # [ 9 18 27 36]
print(a * b) # [ 10 40 90 160]
print(a / b) # [10. 10. 10. 10.]
print(a ** 2) # [ 100 400 900 1600]
Output
[11 22 33 44]
[ 9 18 27 36]
[ 10  40  90 160]
[10. 10. 10. 10.]
[ 100  400  900 1600]
List Comprehension
prices = [10.0, 25.0, 8.5, 42.0]
tax = [p * 0.08 for p in prices]
total = [p + t for p, t in zip(prices, tax)]
print(total)
NumPy Vectorized
import numpy as np
prices = np.array([10.0, 25.0, 8.5, 42.0])
total = prices * 1.08
print(total)

How Do You Summarize an Array with Aggregations?

Aggregation functions reduce an array down to a single value (or a smaller array). These are the bread and butter of data analysis - you'll use them constantly.

aggregations.py
import numpy as np
scores = np.array([85, 92, 78, 95, 88, 76, 91])
print(np.sum(scores)) # 605
print(np.mean(scores)) # 86.42857142857143
print(np.std(scores)) # 6.798542449578686
print(np.min(scores)) # 76
print(np.max(scores)) # 95
print(np.argmin(scores)) # 5 (index of the minimum)
print(np.argmax(scores)) # 3 (index of the maximum)
Output
605
86.42857142857143
6.651683843898752
76
95
5
3

What Does the axis Parameter Do?

For 2D arrays, you often want to sum across rows or across columns, not the entire array. The axis parameter controls which dimension gets collapsed. Think of it as choosing whether to summarize a spreadsheet by rows or by columns.

axis=0 operates down the rows (collapses the row dimension), giving you one value per column. axis=1 operates across the columns (collapses the column dimension), giving you one value per row.

axis_example.py
import numpy as np
# 3 students, 4 exam scores each
grades = np.array([[85, 90, 78, 92],
[70, 88, 95, 80],
[92, 76, 84, 88]])
print(np.sum(grades)) # 1018 (everything)
print(np.sum(grades, axis=0)) # [247 254 257 260] (per exam)
print(np.sum(grades, axis=1)) # [345 333 340] (per student)
print(np.mean(grades, axis=1)) # [86.25 83.25 85. ] (avg per student)
Output
1018
[247 254 257 260]
[345 333 340]
[86.25 83.25 85.  ]

What Are Universal Functions (ufuncs)?

Universal functions (ufuncs) are NumPy functions that operate element-by-element on arrays. They include math functions like np.sqrt, np.exp, np.log, and trigonometric functions. They're fast because they run in compiled C code.

ufuncs.py
import numpy as np
a = np.array([1, 4, 9, 16, 25])
print(np.sqrt(a)) # [1. 2. 3. 4. 5.]
print(np.square(a)) # [ 1 16 81 256 625]
print(np.abs(np.array([-3, -1, 0, 2, 5]))) # [3 1 0 2 5]
# Trigonometry
angles = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2])
print(np.round(np.sin(angles), 2)) # [0. 0.5 0.71 0.87 1. ]
Output
[1. 2. 3. 4. 5.]
[  1  16  81 256 625]
[3 1 0 2 5]
[0.   0.5  0.71 0.87 1.  ]

How Does Boolean Indexing Work?

Boolean indexing lets you filter an array using a condition. When you write a > 5, NumPy creates a boolean array of True/False values. You can then use that boolean array to select only the elements where the condition is True.

boolean_indexing.py
import numpy as np
temps = np.array([68, 72, 85, 90, 55, 78, 95, 62])
# Create a boolean mask
hot_mask = temps > 80
print(hot_mask) # [False False True True False False True False]
# Use the mask to filter
hot_days = temps[hot_mask]
print(hot_days) # [85 90 95]
# Or do it in one step
print(temps[temps >= 70]) # [72 85 90 78 95]
Output
[False False  True  True False False  True False]
[85 90 95]
[72 85 90 78 95]

You can combine conditions using & (and), | (or), and ~ (not). Important: use parentheses around each condition because of operator precedence.

combined_conditions.py
import numpy as np
temps = np.array([68, 72, 85, 90, 55, 78, 95, 62])
# Comfortable range: 65 to 80
comfy = temps[(temps >= 65) & (temps <= 80)]
print(comfy) # [68 72 78]
# Count how many hot days
print(np.sum(temps > 80)) # 3
Output
[68 72 78]
3

What Is Fancy Indexing?

Fancy indexing means passing an array of integer indexes to select specific elements. Unlike slicing, it can pick non-consecutive elements in any order and always returns a copy.

fancy_indexing.py
import numpy as np
names = np.array(['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])
scores = np.array([95, 82, 78, 91, 88])
# Pick specific indexes
top_idx = np.array([0, 3, 4])
print(names[top_idx]) # ['Alice' 'Diana' 'Eve']
print(scores[top_idx]) # [95 91 88]
# Combine with argsort for ranking
ranked = np.argsort(scores)[::-1] # indexes sorted by score, descending
print(names[ranked]) # ['Alice' 'Diana' 'Eve' 'Bob' 'Charlie']
Output
['Alice' 'Diana' 'Eve']
[95 91 88]
['Alice' 'Diana' 'Eve' 'Bob' 'Charlie']

Practice Exercises

Apply Sales Tax
Write Code

Given an array of prices [19.99, 35.50, 8.99, 124.00, 56.75], calculate the total cost after adding 7.5% sales tax. Print the result rounded to 2 decimal places using np.round().

import numpy as np
prices = np.array([19.99, 35.50, 8.99, 124.00, 56.75])
# Calculate total with 7.5% tax and print rounded
Student Grade Summary
Write Code

Given grades = np.array([88, 76, 95, 82, 91, 73, 89, 97]), print the following on separate lines:

1. The mean grade

2. The highest grade

3. The index of the lowest grade

import numpy as np
grades = np.array([88, 76, 95, 82, 91, 73, 89, 97])
# Print mean, max, and index of min
Per-Student Averages
Write Code

Create a 3x4 grades matrix:

[[85, 90, 78, 92],
 [70, 88, 95, 80],
 [92, 76, 84, 88]]

Print the average score for each student (each row) using the axis parameter. Round to 1 decimal place.

import numpy as np
grades = np.array([[85, 90, 78, 92],
[70, 88, 95, 80],
[92, 76, 84, 88]])
# Print per-student average, rounded to 1 decimal
Filter the Hot Days
Write Code

Given temps = np.array([58, 67, 72, 81, 90, 85, 63, 77, 94, 71]), print:

1. All temperatures above 80

2. The count of temperatures between 65 and 80 (inclusive)

import numpy as np
temps = np.array([58, 67, 72, 81, 90, 85, 63, 77, 94, 71])
# Print temps above 80
# Print count of temps between 65 and 80
Predict the ufunc Output
Predict Output

What does the following code print?

import numpy as np
a = np.array([4, 9, 16, 25])
b = np.sqrt(a)
print(b)
print(np.sum(b))
import numpy as np
a = np.array([4, 9, 16, 25])
b = np.sqrt(a)
print(b)
print(np.sum(b))
Rank the Top 3 Scores
Write Code

Given names = np.array(['Alice', 'Bob', 'Charlie', 'Diana', 'Eve']) and scores = np.array([82, 95, 78, 91, 88]), use np.argsort() and fancy indexing to print the names of the top 3 scorers in descending order of score.

import numpy as np
names = np.array(['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])
scores = np.array([82, 95, 78, 91, 88])
# Print top 3 names in descending score order

Harder problems

More problems on this topic: Math

Related Tutorials

Was this tutorial helpful?