Learn NumPy · 8/15

Array Math and Universal Functions (ufuncs)

6 min read

🔢 Array Math and Universal Functions (ufuncs)

Welcome back to our NumPy journey! So far, we've learned how to create and manipulate NumPy arrays. Now, let's get into the real fun: performing mathematical operations on these arrays. This is where NumPy truly shines and will save you a ton of time (and sanity).

1. Element-wise Arithmetic: Vectorized Math Operations

The Problem: Imagine you have two massive lists of numbers, say, the prices of a million items and their corresponding tax rates. To calculate the final price for each item, you'd typically have to loop through each element one by one.

python
# The slow, painful way with regular Python lists
prices = [10, 20, 30, 40, 50]
taxes = [0.1, 0.1, 0.1, 0.1, 0.1]
final_prices = []

for price, tax in zip(prices, taxes):
  final_prices.append(price * tax + price)

print(final_prices)

This works, but for very large datasets, it's like sending a handwritten letter instead of an email – it gets the job done, but it's incredibly slow. 🐌

The Solution: Vectorization!

NumPy allows you to perform these operations on entire arrays at once, without writing a single loop. This is called vectorization. It's the process of applying an operation to a whole array instead of element by element.

Let's see this magic in action:

python
import numpy as np

prices_array = np.array([10, 20, 30, 40, 50])
taxes_array = np.array([0.1, 0.1, 0.1, 0.1, 0.1])

# The super-fast NumPy way!
final_prices_array = prices_array * taxes_array + prices_array

print(final_prices_array)
# Output: [11. 22. 33. 44. 55.]

Look at that! Clean, concise, and lightning-fast. ⚡

What's happening under the hood? NumPy is smart. When you ask it to perform an operation on two arrays of the same size, it applies that operation to each pair of corresponding elements. This is called an element-wise operation. Because these operations are performed in compiled C code (which is much faster than Python), the performance gains are huge.

Here are the basic arithmetic operations you can perform:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • ** (Exponentiation)
python
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])

print("Addition:", arr1 + arr2)
print("Subtraction:", arr2 - arr1)
print("Multiplication:", arr1 * arr2)
print("Division:", arr2 / arr1)
print("Exponentiation:", arr1 ** 2)

Fun Fact: This concept of vectorization is a cornerstone of scientific computing and data science. It allows you to process massive datasets efficiently, which is crucial for tasks like machine learning and data analysis.

2. Mathematical ufuncs: Exponentials, Logs, and Trigonometry

The Problem: What if you need to apply a more complex mathematical function to every element in your array, like finding the sine, cosine, or natural logarithm? Writing a loop for these would again be slow and cumbersome.

The Solution: Universal Functions (ufuncs)!

NumPy provides a whole suite of universal functions, or ufuncs, which are essentially functions that operate on NumPy arrays in an element-wise fashion.

Let's say you have an array of angles in radians and you want to find the sine of each angle.

python
angles = np.array([0, np.pi/2, np.pi])

# No loop needed!
sines = np.sin(angles)

print(sines)
# Output: [0.0000000e+00 1.0000000e+00 1.2246468e-16]
# Note: The last value is a very small number close to 0 due to floating-point precision.

Here are some of the most frequently used mathematical ufuncs:

  • np.exp(): Calculates the exponential of each element.
  • np.log(), np.log2(), np.log10(): Computes the natural, base-2, and base-10 logarithm.
  • np.sin(), np.cos(), np.tan(): The usual trigonometric functions.
python
data = np.array([1, 2, 3])

print("Exponentials:", np.exp(data))
print("Natural Logarithms:", np.log(data))

angles = np.array([0, np.pi/4, np.pi/2])
print("Cosines:", np.cos(angles))

Real-world scenario: Imagine you're analyzing a sound wave, which is often represented as a series of numbers (amplitudes). To perform a Fourier transform (a common signal processing technique), you'd heavily rely on trigonometric ufuncs like np.sin() and np.cos() to analyze its frequency components.

3. Handling Missing Data: Dealing with np.nan and np.isnan()

The Problem: In the real world, data is messy. You'll often encounter datasets with missing values. In NumPy, missing numerical data is represented by np.nan, which stands for "Not a Number".

The tricky part about np.nan is that any arithmetic operation involving it will result in np.nan.

python
messy_data = np.array([1, 2, np.nan, 4])

print("Sum of messy_data:", np.sum(messy_data))
# Output: nan

This can be a real headache because it can silently ruin your calculations. Even a single np.nan can contaminate your entire result. 😫

The Solution: np.isnan() and NaN-safe functions

First, you need to identify where these missing values are. NumPy's np.isnan() function comes to the rescue. It returns a boolean array, with True where the np.nan values are and False everywhere else.

python
messy_data = np.array([1, 2, np.nan, 4])

print("Is it NaN?", np.isnan(messy_data))
# Output: [False False  True False]

Once you've identified the missing values, you have a few options. A common approach in the industry is to either remove them or replace them with a meaningful value (like the mean or median of the rest of the data).

For calculations, NumPy provides NaN-safe versions of some common functions:

  • np.nansum(): Computes the sum, ignoring np.nan values.
  • np.nanmean(): Computes the mean, ignoring np.nan values.
  • np.nanmin(), np.nanmax(): Finds the minimum or maximum, ignoring np.nan values.
python
messy_data = np.array([1, 2, np.nan, 4])

print("Sum ignoring NaN:", np.nansum(messy_data))
# Output: 7.0

Industry Practice: In data analysis, how you handle missing data is a critical step. Simply ignoring it might not always be the best approach. Sometimes, you might want to fill the missing values using techniques like forward-fill, backward-fill, or interpolation, depending on the nature of your data.

4. Rounding Values: round(), floor(), and ceil()

The Problem: Often, you'll be working with floating-point numbers that have more precision than you need. For cleaner outputs or for specific calculations, you might want to round these numbers.

The Solution: NumPy's Rounding Functions

NumPy offers a few handy functions for rounding:

  • np.round(array, decimals=0): Rounds to the given number of decimals.
  • np.floor(array): Rounds down to the nearest integer.
  • np.ceil(array): Rounds up to the nearest integer.

Let's see them in action:

python
float_array = np.array([1.23, 4.56, 7.89])

print("Rounded to 1 decimal place:", np.round(float_array, decimals=1))
# Output: [1.2 4.6 7.9]

print("Floor (rounded down):", np.floor(float_array))
# Output: [1. 4. 7.]

print("Ceiling (rounded up):", np.ceil(float_array))
# Output: [2. 5. 8.]

Real-life scenario: Imagine you're building a financial application that calculates interest. You'll definitely need to round the final amounts to two decimal places, as you can't have fractions of a cent!


📚 For the Curious Minds (Extra Reading)

Challenge

Challenge: Sales Data Analysis

You are a data analyst for an e-commerce company. You have been given two NumPy arrays representing the price of various products and the number of units sold for each over the last week.

Unfortunately, there were some data corruption issues, and some entries in the units_sold array are missing, represented by np.nan.

Your task is to process this data to generate a sales report. You must perform the following calculations using NumPy's vectorized operations and NaN-safe universal functions:

  1. Calculate the revenue for each product. This is done by multiplying the price of each product by the number of units sold. Store this result in a variable named revenue_per_product.
  2. Calculate the total weekly revenue. This should be the sum of all individual product revenues, making sure to ignore the entries affected by missing data. Store this in a variable named total_revenue.
  3. Determine the average number of units sold across all products for which data is available. Store this in average_units.
  4. For the final report, financial figures need to be cleaned up. Create two new variables:
    • report_revenue: The total_revenue rounded down to the nearest integer.
    • report_avg_units: The average_units rounded to exactly one decimal place.

Expected result

Your code should correctly define five variables:

  • revenue_per_product: A NumPy array containing the result of the element-wise multiplication of product_prices and units_sold. This array will contain np.nan values where the units_sold data was missing.
  • total_revenue: A scalar value calculated by summing the revenue_per_product array. The calculation must use a NaN-safe function to correctly ignore missing data.
  • average_units: A scalar value representing the mean of the units_sold array, calculated using a NaN-safe function.
  • report_revenue: The total_revenue scalar, rounded down to the nearest whole number using np.floor().
  • report_avg_units: The average_units scalar, rounded to one decimal place using np.round().
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.