Learn NumPy Β· 11/15

Sorting, Searching, and Counting

8 min read

Course: NumPy

Topic: Sorting, Searching, and Counting πŸ”’

Welcome, aspiring data wrangler! Today, we're diving into the essential skills of sorting, searching, and counting within NumPy. Think of this as organizing your massive digital library. Without a good system, finding anything would be a nightmare. These NumPy functions are your super-powered librarians, ready to bring order to the chaos of data.


1. Sorting Arrays: np.sort() vs In-place Sorting SORT

The Problem: You have an array of numbers, say, the scores of students on a test, and you need to arrange them in ascending order to easily see the ranking. How do you do this efficiently without manually reordering everything?

The Solution: NumPy provides a powerful and straightforward function called np.sort().

np.sort(): The "Make a Copy and Organize" Approach

The np.sort() function takes an array and returns a new, sorted copy of it. The original array remains untouched. This is like having a messy desk, taking a picture of it, and then tidying up the picture, while your actual desk remains as gloriously chaotic as ever.

Syntax:

python
numpy.sort(a, axis=-1, kind=None, order=None)

Let's Break It Down:

  • a: The array you want to sort.
  • axis: The axis along which to sort. If None, the array is flattened before sorting. The default is -1, which means sort along the last axis.
  • kind: The sorting algorithm. The default is 'quicksort'. You'll rarely need to change this, but it's good to know it's there.
  • order: If the array contains fields, this specifies which fields to sort by.

Example: A Simple Sort

python
import numpy as np

# Let's say these are the number of donuts eaten by your friends this week 🍩
donuts_eaten = np.array([5, 2, 8, 1, 9])

# Let's sort this to see who has the most self-control
sorted_donuts = np.sort(donuts_eaten)

print("Original array:", donuts_eaten)
print("Sorted array:", sorted_donuts)

Output:

tap
Original array: [5 2 8 1 9]
Sorted array: [1 2 5 8 9]

Notice how donuts_eaten is still in its original, chaotic order. np.sort() gave us a brand new, organized array.

In-place Sorting: The "Tidy Up Your Actual Desk" Approach

Sometimes, you don't need to keep the original messy version. You just want to sort the array you have and save memory by not creating a new one. This is called "in-place" sorting. For this, you use the .sort() method of the array object itself.

Syntax:

python
a.sort(axis=-1, kind=None, order=None)

Example: Sorting In-Place

python
import numpy as np

# Ages of people in a room
ages = np.array([34, 12, 45, 23, 28])

# Let's sort the ages directly
ages.sort()

print("Ages in the room (now sorted):", ages)

Output:

inform7
Ages in the room (now sorted): [12 23 28 34 45]

Here, the ages array itself has been changed.

np.sort() vs. In-place .sort(): Which one to use?

  • Use np.sort() when you need to keep the original array intact. This is the more common and generally safer approach in data analysis, as you often want to preserve your original data.
  • Use the in-place .sort() method when you're sure you won't need the original order anymore and want to be more memory-efficient.

A Funny Exaggeration: Using in-place sort without thinking is like tidying your room by throwing everything you don't immediately need out the window. It's clean, sure, but you might regret it later.


2. Indirect Sorting: Unlocking the Magic of np.argsort() πŸͺ„

The Problem: You have a list of student names and another list of their corresponding scores. You want to rank the students from highest to lowest score, but if you sort the scores, how do you know which name corresponds to which new score position?

The Solution: np.argsort() comes to the rescue! Instead of sorting the values themselves, it gives you the indices of the sorted elements.

Imagine you have a line of people of different heights. Instead of rearranging the people, you just write down the position of the shortest person, then the second shortest, and so on. That list of positions is what np.argsort() gives you.

Syntax:

python
numpy.argsort(a, axis=-1, kind=None, order=None)

Example: Ranking Students

python
import numpy as np

students = np.array(['Alice', 'Bob', 'Charlie', 'David'])
scores = np.array([85, 92, 78, 95])

# Get the indices that would sort the scores
sorted_indices = np.argsort(scores)

print("Original scores:", scores)
print("Sorted indices:", sorted_indices)

# Now, use these indices to rearrange the students and scores
print("Students sorted by score:", students[sorted_indices])
print("Scores sorted:", scores[sorted_indices])

Output:

less
Original scores: [85 92 78 95]
Sorted indices: [2 0 1 3]
Students sorted by score: ['Charlie' 'Alice' 'Bob' 'David']
Scores sorted: [78 85 92 95]

How it works under the hood: np.argsort() looks at the scores array [85, 92, 78, 95]. It finds the smallest value, 78, which is at index 2. Then it finds the next smallest, 85, at index 0. It continues this until it has a list of indices: [2, 0, 1, 3]. You can then use this "recipe" to reorder any other array that corresponds to the original data.


3. Searching for Elements: np.searchsorted() πŸ”

The Problem: You have a sorted array, and you want to find the position where a new element could be inserted while keeping the array sorted. This is a very common task, for example, when you want to categorize data into bins.

The Solution: np.searchsorted() is a highly efficient way to do this. It performs a binary search, which is much faster than checking each element one by one.

Think of it like finding a word in a physical dictionary. You don't start from the first page and read every word. You open it roughly in the middle and decide whether to go forward or backward, narrowing down the search space by half each time.

Syntax:

python
numpy.searchsorted(a, v, side='left', sorter=None)
  • a: The sorted input array.
  • v: The value(s) to insert.
  • side: If 'left', it returns the first suitable index. If 'right', it returns the last.

Example: Placing a New Score

python
import numpy as np

# A sorted array of scores
sorted_scores = np.array([60, 72, 78, 85, 92, 95])

# Where would a new score of 80 go?
insertion_point = np.searchsorted(sorted_scores, 80)

print("Sorted scores:", sorted_scores)
print("A score of 80 should be inserted at index:", insertion_point)

Output:

mipsasm
Sorted scores: [60 72 78 85 92 95]
A score of 80 should be inserted at index: 3

This tells us that if we insert 80 at index 3, the array [60, 72, 78, 80, 85, 92, 95] will remain sorted.


4. Finding Uniques and Counts: np.unique() and np.bincount() πŸ“Š

The Problem: You have a dataset with many repeated values, and you need to find out which unique values exist and how many times each one appears. For instance, you have a list of items sold, and you want a summary of unique items and their sale counts.

The Solution: np.unique() and np.bincount() are your go-to functions.

np.unique(): The "What do I have and how many?" Function

np.unique() is incredibly useful. It returns the sorted unique elements of an array. It can also optionally return the indices of the first occurrences and the counts of each unique element.

Syntax:

python
numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)

Example: Analyzing Survey Responses

python
import numpy as np

# Survey responses for a favorite color
colors = np.array(['blue', 'red', 'green', 'blue', 'red', 'blue'])

# Find the unique colors and how many votes each got
unique_colors, counts = np.unique(colors, return_counts=True)

print("Unique colors:", unique_colors)
print("Counts:", counts)

# We can now create a nice summary
for color, count in zip(unique_colors, counts):
    print(f"- {color}: {count} votes")

Output:

processing
Unique colors: ['blue' 'green' 'red']
Counts: [3 1 2]
- blue: 3 votes
- green: 1 votes
- red: 2 votes

np.bincount(): The Super-Fast Counter for Integers

When your array consists of non-negative integers, np.bincount() is a highly optimized way to count the occurrences of each number. It creates "bins" for each integer and counts how many times that integer appears.

Important: This only works for non-negative integers.

Syntax:

python
numpy.bincount(x, weights=None, minlength=0)

Example: Counting Dice Rolls

python
import numpy as np

# 10 rolls of a 6-sided die (indices 1 to 6)
# Note: We can't have a 0 on a die, but bincount will create a bin for 0.
dice_rolls = np.array([1, 4, 2, 5, 2, 6, 1, 3, 2, 4])

# Count the occurrences of each number
roll_counts = np.bincount(dice_rolls)

print("Roll counts (index 0 is unused):", roll_counts)

# Let's print this more clearly
for i in range(1, len(roll_counts)):
    print(f"Number {i} was rolled {roll_counts[i]} times.")

Output:

tap
Roll counts (index 0 is unused): [0 2 3 1 2 1 1]
Number 1 was rolled 2 times.
Number 2 was rolled 3 times.
Number 3 was rolled 1 times.
Number 4 was rolled 2 times.
Number 5 was rolled 1 times.
Number 6 was rolled 1 times.

Interesting Fact: np.bincount() is often significantly faster than np.unique() for this specific task because it can directly use the integer values as indices, avoiding more complex sorting and comparison operations.


πŸ“š References for Extra Reading

Challenge

You are a data analyst for a marathon event. You have been provided with three NumPy arrays:

  • racer_ids: Unique integer IDs for each participant.
  • finish_times: The finish time in seconds for each corresponding racer.
  • category_codes: An integer code representing the racer's category (0 for 'Junior', 1 for 'Senior').

Your task is to process this data to generate a leaderboard, count participants in each category, and classify racers into performance tiers.

Requirements:

  1. Generate the Leaderboard:

    • Determine the correct sorting order based on finish_times (lowest time is best).
    • Apply this order to the racer_ids array to create the final leaderboard. The first ID in the leaderboard should be the winner.
  2. Count Participants by Category:

    • Using the category_codes array, efficiently count the number of participants in category 0 and category 1.
    • Store the result in the category_counts variable. The resulting array should show the count for category 0 at index 0 and the count for category 1 at index 1.
  3. Determine Performance Tiers:

    • The performance tiers are defined by these time thresholds: Gold (< 10000s) and Silver (>= 10000s and < 12000s).
    • First, create a new, sorted copy of the finish_times and store it in sorted_times.
    • Using the sorted_times array and the time_thresholds, find the number of racers who qualify for the Gold tier and store it in gold_tier_count.
    • Find the number of racers who qualify for the Silver tier and store it in silver_tier_count.

Expected result

Your code should correctly populate the placeholder variables.

  • The leaderboard variable should be a NumPy array containing the racer IDs sorted by their finish times in ascending order:
    tap
    [107 102 101 106 105 104 108 103]
  • The category_counts variable should be a NumPy array showing that there are 4 racers in each category:
    angelscript
    [4 4]
  • The sorted_times variable should hold a new array with the finish times sorted in ascending order.
  • The gold_tier_count variable should be the integer 2, as two racers finished in under 10000 seconds.
  • The silver_tier_count variable should be the integer 4, representing the racers who finished between 10000 and 11999 seconds.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.