Learn NumPy Β· 10/15

Aggregations and Statistics: Summarizing Your Data

5 min read

Aggregations and Statistics: Summarizing Your Data 🧹

Ever felt like you're drowning in a sea of data? 🌊 You've got this massive NumPy array, and you need to make sense of it. Looking at each individual number is like trying to understand a book by reading every letter one by one. Not very efficient, right? That's where aggregations and statistics come to the rescue! These are functions that take your array and boil it down to a single, meaningful value.

Think of it like this: you've just done a survey of the heights of all the students in a school. Instead of a long list of numbers, you probably want to know things like the average height, the tallest person, and the shortest person. These summary statistics give you a high-level understanding of your data without getting lost in the details.

In the world of data science and machine learning, you'll be doing this all the time. From calculating the average error of a model to finding the maximum value in a sensor reading, aggregations are a fundamental tool in your data analysis toolkit.

So, let's dive in and see how NumPy makes this incredibly easy and efficient!

Basic Aggregations: sum(), min(), and max() βž•βž–

Let's start with the big three of aggregations. You'll find yourself reaching for these constantly.

  • np.sum(): Adds up all the elements in your array.
  • np.min(): Finds the smallest element.
  • np.max(): Finds the largest element.

These functions are pretty straightforward, but their power lies in their speed. NumPy performs these calculations in highly optimized C code, which is way faster than doing it with a standard Python loop.

Let's imagine you're a shop owner tracking your daily sales for a week.

python
import numpy as np

# Daily sales for a week
daily_sales = np.array([120, 150, 135, 180, 210, 200, 190])

# What's the total revenue for the week?
total_revenue = np.sum(daily_sales)
print(f"Total Revenue: ${total_revenue}")

# What was the best sales day?
best_day = np.max(daily_sales)
print(f"Best Sales Day: ${best_day}")

# And the not-so-greatest day?
worst_day = np.min(daily_sales)
print(f"Worst Sales Day: ${worst_day}")

See? Simple and intuitive. You can also call these as methods directly on the NumPy array object itself, which some people find more readable.

python
# The method way
total_revenue_method = daily_sales.sum()
best_day_method = daily_sales.max()
worst_day_method = daily_sales.min()

The Power of axis: Calculating Down Rows or Across Columns ↔️↕️

Now, what if your data has more than one dimension? Let's say you're tracking sales for two different shops over a week.

python
# Sales for two shops over a week
# Shop 1 is the first row, Shop 2 is the second
shop_sales = np.array([
    [120, 150, 135, 180, 210, 200, 190],
    [110, 160, 140, 175, 200, 195, 185]
])

If you just call np.sum(shop_sales), you'll get the grand total of sales across both shops for the entire week. But what if you want to know the total sales for each shop individually? Or the total sales for each day across both shops?

This is where the magical axis parameter comes in. It lets you specify the direction of your calculation.

  • axis=0: Performs the operation down the rows (column-wise). Think of it as collapsing the rows together.
  • axis=1: Performs the operation across the columns (row-wise). This collapses the columns.

Let's see it in action:

python
# Total sales for each day (summing down the columns)
daily_totals = np.sum(shop_sales, axis=0)
print(f"Total sales per day: {daily_totals}")

# Total sales for each shop (summing across the rows)
shop_totals = np.sum(shop_sales, axis=1)
print(f"Total sales per shop: {shop_totals}")

A Fun Fact to Remember axis: Imagine your 2D array is a spreadsheet. axis=0 is like highlighting a whole column and clicking the "sum" button at the bottom. axis=1 is like doing the same for a row and seeing the sum at the end.

Statistical Measures: mean(), median(), var(), and std() πŸ“Š

Beyond the basics, NumPy provides a whole suite of statistical functions to dig deeper into your data. Here are some of the most common ones:

  • np.mean(): Calculates the average of your data.
  • np.median(): Finds the middle value when your data is sorted. This is often more robust to outliers than the mean.
  • np.var(): Measures the variance, which tells you how spread out your data is.
  • np.std(): Calculates the standard deviation, which is the square root of the variance and is also a measure of spread.

Let's say we have the test scores of a class.

python
scores = np.array([88, 92, 85, 78, 95, 62, 89, 91, 84])

# What's the average score?
average_score = np.mean(scores)
print(f"Average score: {average_score}")

# What's the median score?
median_score = np.median(scores)
print(f"Median score: {median_score}")

# How much do the scores vary?
score_variance = np.var(scores)
print(f"Score variance: {score_variance}")

# What's the standard deviation?
score_std_dev = np.std(scores)
print(f"Score standard deviation: {score_std_dev}")

And yes, you can use the axis parameter with all of these functions as well! This is incredibly useful for comparing statistics across different groups in your data.

Finding Extreme Indices: argmin() and argmax() πŸ•΅οΈβ€β™€οΈ

Sometimes, you don't just want to know the minimum or maximum value; you want to know where that value is. This is where argmin() and argmax() come in handy.

  • np.argmin(): Returns the index of the minimum value.
  • np.argmax(): Returns the index of the maximum value.

Let's go back to our daily sales example.

python
daily_sales = np.array([120, 150, 135, 180, 210, 200, 190])

# On which day did we have the highest sales? (Remember, indices start at 0)
best_day_index = np.argmax(daily_sales)
print(f"The best sales day was on day index: {best_day_index}")

# And the worst?
worst_day_index = np.argmin(daily_sales)
print(f"The worst sales day was on day index: {worst_day_index}")

Real-World Scenario: Imagine you have a dataset of house prices and you want to find the house with the highest price. argmax() would give you the index of that house in your array, allowing you to then look up its other features.

And, you guessed it, argmin() and argmax() also work with the axis parameter for multi-dimensional arrays!


πŸ“š Further Reading and References:

  • Official NumPy Documentation: The ultimate source of truth for all things NumPy.
  • NumPy sum() documentation:
  • NumPy mean() documentation:
  • NumPy std() documentation:
  • NumPy argmin() documentation:
  • NumPy argmax() documentation:

Challenge

You are provided with a 2D NumPy array named temperatures. This array contains the daily temperature readings (in Celsius) from 4 different weather stations over a 7-day period. Each row represents a different station, and each column represents a day of the week (from Monday to Sunday).

Your task is to perform a series of statistical analyses on this data and store the results in the provided variables.

  1. daily_total_temps: Calculate the sum of temperatures for each day across all four stations. The result should be a 1D array with 7 elements.
  2. station_max_temps: Determine the highest temperature recorded for each of the four stations during the week. The result should be a 1D array with 4 elements.
  3. station_avg_temps: Compute the average weekly temperature for each of the four stations. The result should be a 1D array with 4 elements.
  4. coldest_day_index: Identify the index of the day (0-6) that had the lowest average temperature across all stations. This should be a single integer value.
  5. overall_std_dev: Calculate the standard deviation for the entire set of temperature readings. This should be a single float value.

Expected result

Your code should correctly populate the five variables with the results of your analysis:

  • daily_total_temps should be a NumPy array containing the sum of temperatures for each day, which will be [90.3, 94.5, 95.4, 91.3, 85.3, 81.8, 89.9].
  • station_max_temps should be a NumPy array containing the maximum temperature for each station, which will be [24. , 26.1, 21.5, 25.1].
  • station_avg_temps should be a NumPy array containing the average weekly temperature for each station, approximately [22.029, 23.929, 19.786, 24.043].
  • coldest_day_index should be an integer representing the index of the day with the lowest average temperature, which is 5.
  • overall_std_dev should be a float representing the standard deviation of all temperatures, approximately 2.189.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.