In this tutorial, you will learn advanced operations with NumPy arrays including sorting, searching, combining, and splitting arrays using various powerful NumPy functions such as np.sort()
, np.where()
, np.concatenate()
, and np.split()
.
1. Sorting Arrays (np.sort())
The np.sort()
function returns a sorted version of an array in ascending order by default.
Syntax:
numpy.sort(array, axis=-1)
array: This is the NumPy array you want to sort, like [4, 2, 7, 1] for a 1D case or [[3, 1], [4, 2]] for a 2D case. It’s the input data that numpy.sort() will organize in ascending order, creating a new sorted array without changing the original.
axis: This parameter tells numpy.sort() which direction to sort along. When set to -1, it automatically picks the last axis of the array. For a 1D array, that’s just the only axis (axis 0), sorting it to [1, 2, 4, 7]. For a 2D array, the last axis is the columns (axis 1), so it sorts each row individually, turning [[3, 1], [4, 2]] into [[1, 3], [2, 4]]. It’s a handy default for sorting the innermost dimension.
Example:
import numpy as np
arr = np.array([4, 2, 7, 1, 9])
# Sort in ascending order
sorted_arr = np.sort(arr)
print("Sorted Array (ascending):", sorted_arr)
# Sort in descending order
desc_sorted_arr = np.sort(arr)[::-1]
print("Sorted Array (descending):", desc_sorted_arr)
Output:
Sorted Array (ascending): [1 2 4 7 9]
Sorted Array (descending): [9 7 4 2 1]
The code imports NumPy as np and creates an array arr with numbers [4, 2, 7, 1, 9]. It sorts this array in ascending order using np.sort(arr), resulting in [1, 2, 4, 7, 9], and prints it. For descending order, it uses np.sort(arr)[::-1], which sorts the array then reverses it to [9, 7, 4, 2, 1], and prints that too. The original array stays unchanged, and both sorted versions are displayed.
2. Searching in Arrays (np.where())
The np.where()
function returns indices of elements satisfying a given condition.
Syntax:
numpy.where(condition)
condition: This is a boolean expression applied to a NumPy array, like arr > 25 for an array arr = np.array([10, 20, 30, 40, 50]). It evaluates each element, returning True or False—here, it’d be [False, False, True, True, True]. The numpy.where() function uses this to find the indices where the condition is True, outputting (array([2, 3, 4]),) for positions of 30, 40, and 50. It returns a tuple of arrays, one for each axis, showing where the condition holds.
Example:
arr = np.array([10, 20, 30, 40, 50])
# Find indices of elements greater than 25
indices = np.where(arr > 25)
print("Indices of elements greater than 25:", indices)
# Elements greater than 25
print("Elements greater than 25:", arr[indices])
Output:
Indices of elements greater than 25: (array([2, 3, 4]),)
Elements greater than 25: [30 40 50]
This code creates a NumPy array arr with values [10, 20, 30, 40, 50]. Using np.where(arr > 25), it finds the indices (2, 3, 4) where elements are greater than 25 and stores them in indices. It then prints these indices and uses them to extract and print the corresponding elements [30, 40, 50] from the array with arr[indices]. Essentially, it identifies and displays both the positions and values of numbers exceeding 25.
3. Combining Arrays (np.concatenate())
The np.concatenate()
function joins two or more arrays along a specified axis.
Syntax:
numpy.concatenate((array1, array2, ...), axis=0)
array1, array2, …: These are the NumPy arrays you want to join together, like array1 = np.array([1, 2, 3]) and array2 = np.array([4, 5, 6]). They’re passed as a tuple to numpy.concatenate(), which combines them into a single array. For example, with these arrays, it produces [1, 2, 3, 4, 5, 6] when using the default axis.
axis: This specifies the direction of concatenation. When set to 0 (the default), it stacks the arrays along the first axis (rows for 2D arrays). For 1D arrays like above, it simply joins them end-to-end. For 2D arrays, say [[1, 2], [3, 4]] and [[5, 6], [7, 8]], axis=0 stacks them vertically into [[1, 2], [3, 4], [5, 6], [7, 8]]. Changing it to axis=1 would stack horizontally instead, if the shapes allow.
Example:
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Combine arrays horizontally
combined = np.concatenate((arr1, arr2))
print("Combined Array:", combined)
Output:
Combined Array: [1 2 3 4 5 6]
Here we create two NumPy arrays: arr1 with values [1, 2, 3] and arr2 with [4, 5, 6]. It uses np.concatenate((arr1, arr2)) to combine them horizontally into a single array, resulting in [1, 2, 3, 4, 5, 6], which is stored in combined. Finally, it prints this new array with the message “Combined Array: [1 2 3 4 5 6]”. The np.concatenate() function simply joins the arrays end-to-end in the order provided.
4. Splitting Arrays (np.split())
The np.split()
function splits an array into multiple sub-arrays.
Syntax:
numpy.split(array, indices_or_sections)
array: This is the NumPy array you want to divide, like arr = np.array([10, 20, 30, 40, 50, 60]). It’s the input that numpy.split() will break into smaller sub-arrays based on the provided indices_or_sections.
indices_or_sections: This defines how to split the array. If it’s an integer, like 3, it splits the array into that many equal parts, here resulting in [array([10, 20]), array([30, 40]), array([50, 60])]. If it’s a list of indices, like [2, 4], it splits at those positions, giving [array([10, 20]), array([30, 40]), array([50, 60])] (up to index 2, then 4, then the rest). The array’s length must be evenly divisible by the number of sections when using an integer, or match the cut points when using indices.
Example:
arr = np.array([10, 20, 30, 40, 50, 60])
# Split into 3 sub-arrays
split_arr = np.split(arr, 3)
print("Split Arrays:", split_arr)
Output:
Split Arrays: [array([10, 20]), array([30, 40]), array([50, 60])]
This code creates a NumPy array arr with values [10, 20, 30, 40, 50, 60]. It uses np.split(arr, 3) to divide the array into 3 equal sub-arrays, resulting in [array([10, 20]), array([30, 40]), array([50, 60])], which is stored in split_arr. Then, it prints these sub-arrays with the message “Split Arrays: [array([10, 20]), array([30, 40]), array([50, 60])]“. The np.split() function splits the original array into the specified number of equal parts, here creating three pairs of numbers.
Summary Table
Function | Description |
---|---|
np.sort() | Sort arrays in ascending/descending order |
np.where() | Search for elements based on condition |
np.concatenate() | Combine arrays along a specified axis |
np.split() | Split array into multiple sub-arrays |