Sitemap
Aamer Paul

Aamer Paul

Software Engineer | 8+ yrs experience | Java, Kotlin, Python, JS/TS, Spring Boot, Microservices & Mobile Dev | Exploring Backend, ML, Generative AI & LLMs

NumPy Array Manipulation

8 min readFeb 24, 2024

--

Press enter or click to view image in full size
Photo by Jakob Braun on Unsplash

Welcome to my blog series on NumPy. In this post, we’ll dive into the world of NumPy array manipulation, exploring how to reshape, combine, and split arrays for better data handling.

Before diving in, be sure to check out my previous post.

In NumPy, arrays can be manipulated in various ways using a wide range of functions and methods. Here are some common approaches to array manipulation in NumPy.

Reshaping

NumPy provides functions like reshape, ravel, flatten, transpose to change the shape of an array. These functions does not modify the original array but returns a new array (except for ravel).

The reshape function gives a new shape to an array without modifying its data.

arr1 = np.array([
[0, 1, 2, 3],
[6, 7, 8, 9],
[12, 13, 14, 15],
])

new_arr = arr1.reshape(6, 2)
print(new_arr)
# [[ 0 1]
# [ 2 3]
# [ 6 7]
# [ 8 9]
# [12 13]
# [14 15]]

When using reshape function, we need to make sure the total number of elements remains the same in both shapes. For example, if we try to reshape the arr1 to shape (4, 4), we will get following error:

arr1.reshape((4,4))
ValueError: cannot reshape array of size 12 into shape (4,4)

If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated.

In following example, arr1.reshape(-1, 2), NumPy will automatically calculate the size for the first dimension such that the total number of elements remains the same after reshaping, and the second dimension will be set to 2. So, arr1.reshape(-1, 2) will reshape the array arr1 from shape (3, 4) to shape (6, 2).

print(arr1.reshape(-1, 2))
# [[ 0 1]
# [ 2 3]
# [ 6 7]
# [ 8 9]
# [12 13]
# [14 15]]

The transpose function returns an array with axes transposed.

arr1 = np.array([
[0, 1, 2, 3],
[6, 7, 8, 9],
[12, 13, 14, 15],
])

# transpose - after transpose shape is (4, 3)
print(np.transpose(arr1)) # or use `arr1.T`
# [[ 0 6 12]
# [ 1 7 13]
# [ 2 8 14]
# [ 3 9 15]]

Both ravel and flatten are used to convert multi-dimensional arrays into one-dimensional arrays, but they differ in their behavior regarding memory management.

ravel:

  • Returns a flattened array, but it does not create a copy of the original array if the elements are contiguous in memory.
  • It returns a flattened view of the original array whenever possible.
  • If the memory layout of the original array is not contiguous, ravel will create a copy.
  • Changes made to the flattened array will affect the original array.

flatten:

  • Always returns a copy of the original array, even if the memory layout is contiguous.
  • It ensures that the returned array is always a new array in memory.
  • Changes made to the flattened array will not affect the original array.
ravelled_arr = arr1.ravel()
flattened_arr = arr1.flatten()

# modify first element
ravelled_arr[0] = 999
flattened_arr[1] = 888

print("original arr1: ", arr1)
# original arr1:
# [[999 1 2 3]
# [ 6 7 8 9]
# [ 12 13 14 15]]
print("ravelled arr: ", ravelled_arr)
# ravelled arr: [999 1 2 3 6 7 8 9 12 13 14 15]
print("flattened arr: ", flattened_arr)
# flattened arr: [ 0 888 2 3 6 7 8 9 12 13 14 15]

We can see in above example, changes in ravelled_arr are reflected in original array arr1.

Concatenation and Splitting

NumPy provides functions like concatenate, stack, hstack, vstack for combining arrays along different axes, and functions like split, hsplit, vsplit for splitting arrays into smaller ones. Lets start with Concatenation first.

concatenate(): Concatenates arrays along a specified axis.

arr1 = np.array([[1, 2, 3], [3, 4, 6]])
arr2 = np.array([[5, 6, 7]])

arr3 = np.concatenate((arr1, arr2))
print(arr3)
# [[1 2 3]
# [3 4 6]
# [5 6 7]]


arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6, 7], [8, 9, 10]])

arr3 = np.concatenate((arr1, arr2), axis=1)
print(arr3)
# [[ 1 2 5 6 7]
# [ 3 4 8 9 10]]

Note: The shapes of the arrays must be compatible along the specified axis for concatenation to occur without errors.

vstack and hstack:

  • vstack stacks arrays vertically (along axis 0).
  • hstack stacks arrays horizontally (along axis 1).
# Stacking arrays vertically
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([[7, 8, 9]])
stacked_vertically = np.vstack((arr1, arr2))
print(stacked_vertically)
# [[1 2 3]
# [4 5 6]
# [7 8 9]]

# Stacking arrays horizontally
arr3 = np.array([[7, 8], [9, 10]])
stacked_horizontally = np.hstack((arr1, arr3))
print(stacked_horizontally)
# [[ 1 2 3 7 8]
# [ 4 5 6 9 10]]

Splitting:

NumPy provides functions to split arrays into smaller ones. Following are some of the common functions for splitting arrays in NumPy. Also, just for readability lets define a function that prints the splitted array.

def print_arr(arr):
for e in arr:
print(e)

split(): Splits an array into multiple sub-arrays along a specified axis.

arr1 = np.arange(9) # [0 1 2 3 4 5 6 7 8]
split_arr = np.split(arr1, 3)
print_arr(split_arr)
# [0 1 2]
# [3 4 5]
# [6 7 8]

# we can also specify `axis`
arr1 = np.array([[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12]])
split_arr = np.split(arr1, 3, axis=1)
print_arr(split_arr)
# [[1 2], [7 8]]
# [[ 3 4], [ 9 10]]
# [[ 5 6], [11 12]]

hsplit and vsplit:

  • hsplit splits an array horizontally (along axis 1).
  • vsplit splits an array vertically (along axis 0).
# Splitting an array horizontally into 3 sub-arrays
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
h_split = np.hsplit(arr1, 3)
print_arr(h_split)
# [[1], [4]]
# [[2], [5]]
# [[3], [6]]

# Splitting an array vertically into 3 sub-arrays
arr1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
v_split = np.vsplit(arr1, 3)
print_arr(v_split)
# [[1 2 3]]
# [[4 5 6]]
# [[7 8 9]]

We can also specify the number of sub-arrays we want along the corresponding axis. Here’s an example:

# Creating an array with shape (6, 4)
arr1 = np.arange(24).reshape(6, 4)

# Splitting the array vertically into 3 sub-arrays (2 rows, and 4 columns)
v_split = np.vsplit(arr1, (2, 4))
print_arr(v_split)
# [[0 1 2 3], [4 5 6 7]]
# [[ 8 9 10 11], [12 13 14 15]]
# [[16 17 18 19], [20 21 22 23]]

Adding and Removing Elements:

NumPy provides functions like append, insert, and delete add or remove elements from arrays. Theses functions does not modify the original array in place. Instead, they return a new array with the desired modifications applied.

  1. append: appends elements to the end of the array along the specified axis.
  2. insert: inserts elements before the given index along the specified axis.
  3. delete: deletes elements at the specified index along the specified axis.
# Appending
arr1 = np.full((2, 3), 99)
new_arr = np.append(arr1, [1, 2, 3])
print(new_arr)
# [99 99 99 99 99 99 1 2 3]

When axis is specified, values must have the correct shape. new_arr = np.append(arr1, [1, 2, 3], axis=0) will throw error:

Get Aamer Paul’s stories in your inbox

Join Medium for free to get updates from this writer.

“ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)”

arr1 = np.full((2, 3), 99)
new_arr = np.append(arr1, [[1, 2, 3]], axis=0)
print(new_arr)
# [[99 99 99]
# [99 99 99]
# [ 1 2 3]]

new_arr = np.append(arr1, [[1], [2]], axis=1)
print(new_arr)
# [[99 99 99 1]
# [99 99 99 2]]
# Inserting Elements
arr1 = np.full((2, 3), 99)
new_arr = np.insert(arr1, 1, 5) # Insert 5 at index 1
print(new_arr)
# [99 5 99 99 99 99 99]

new_arr = np.insert(arr1, 1, 5, axis=0) # Insert row [5, 5, 5] at index 1
print(new_arr)
# [[99 99 99]
# [ 5 5 5]
# [99 99 99]]
# Deleting elements
arr1 = np.arange(1, 10).reshape((3, 3))
print(arr1)
# [[1 2 3]
# [4 5 6]
# [7 8 9]]

new_arr = np.delete(arr1, 2) # Delete element at index 2
print(new_arr)
# [1 2 4 5 6 7 8 9]

new_arr = np.delete(arr1, 2, axis=1) # Delete third column
print(new_arr)
# [[1 2]
# [4 5]
# [7 8]]

Sorting

In NumPy, sorting refers to arranging the elements of an array in a particular order, typically in ascending or descending order. NumPy provides several functions for sorting arrays.

np.sort():

  • This function returns a sorted copy of an array.
  • By default, it sorts the array along the last axis. However, we can specify the axis along which to sort using the axis parameter. (axis: default value is -1)
  • It does not modify the original array; instead, it returns a new array with elements sorted.
  • We can select the sorting algorithm by specifying the kind argument, which accepts options such as {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’} (optional).

Example:

arr1 = np.array([3, 1, 2])
sorted_arr = np.sort(arr1)
print(sorted_arr)
# [1 2 3]

np.argsort():

  • This function returns the indices that would sort an array.
  • Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.
  • Instead of sorting the array itself, it returns an array of indices that specify the order of elements when sorted.
  • It can be useful when you need to sort one array based on the order of another array.

Example:

arr1 = np.array([3, 1, 2])
indices = np.argsort(arr1)
print(indices)
# [1 2 0]

ndarray.sort():

  • This method sorts the array in place.
  • Unlike np.sort(), it modifies the original array.
  • We can select the sorting algorithm by specifying the kind argument, which accepts options such as {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’} (optional).

Example:

arr1 = np.array([3, 1, 2])
arr1.sort()
print(arr1)
# [1 2 3]

np.lexsort():

  • This function performs an indirect sort using a sequence of keys.
  • It is useful for sorting multiple arrays based on a single sort key.

Example: (Sort names: first by last_name, then by first_name)

first_names = ('Mark', 'Amy', 'John')
last_names = ('Taylor', 'Walker', 'Ason')
result = np.lexsort((first_names, last_names)) # Sort 'last_names' first, then 'firstnames'
print(result)
# [2 0 1]

Unique and Set Operations:

In NumPy, unique and set operations refer to functions for identifying unique elements in arrays and performing set operations on arrays. These operations are useful for data manipulation and analysis tasks. Lets start with unique operations first.

Unique Operations:

np.unique():

  • The function returns the sorted unique elements of an array.
  • When the parameter return_index is set to True, the function also returns the indices of the original array corresponding to the unique sorted array elements.
  • When the parameter return_inverse is set to True, the function also returns an array (indices) that maps the original array to the unique values. The returned indices can be used to reconstruct array.

Example:

arr1 = np.array([2, 3, 1, 4, 1, 2, 4])
unique_elements = np.unique(arr1)
print(unique_elements)
# [1 2 3 4]

_, unique_elements_indicies = np.unique(arr1, return_index=True)
print(unique_elements_indicies)
# [2 0 1 3]

_, unique_elements_indicies = np.unique(arr1, return_inverse=True)
print(unique_elements_indicies)
# [1 2 0 3 0 1 3]

np.in1d():

  • This function tests whether each element of a 1D array is also present in a second array.
  • It returns a boolean array of the same shape as the first array, indicating whether each element is found in the second array.
  • When parameter invert is set to True, it inverts the boolean array.

Example:

arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([2, 3, 7])
result = np.in1d(arr1, arr2)
print(result)
# [False True True False]

result = np.in1d(arr1, arr2, invert=True)
print(result)
# [ True False False True]

Set Operations

  1. Union: Combines unique elements from multiple arrays into a single array.
  2. Intersection: Returns the common elements between two arrays.
  3. Set Difference: Returns the elements that are unique to the first array but not present in the second array.
  4. Symmetric Difference: Returns the elements that are unique to each array.

Example:

# union
arr1 = np.array([1, 2, 3])
arr2 = np.array([2, 3, 4, 5])
union = np.union1d(arr1, arr2)
print(union)
# [1 2 3 4 5]

# intersection
intersection = np.intersect1d(arr1, arr2)
print(intersection)
# [2 3]

# Set Difference
difference = np.setdiff1d(arr1, arr2)
print(difference)
# [1]

# Symmetric Difference
symmetric_difference = np.setxor1d(arr1, arr2)
print(symmetric_difference)
# [1 4 5]

--

Aamer Paul
Aamer Paul

Written by Aamer Paul

Software Engineer | 8+ yrs experience | Java, Kotlin, Python, JS/TS, Spring Boot, Microservices & Mobile Dev | Exploring Backend, ML, Generative AI & LLMs