Understanding numpy.insert() function (4 examples)

Updated: March 2, 2024 By: Guest Contributor Post a comment

Overview

The Numpy library in Python is a cornerstone for the scientific computation ecosystem, providing efficient array operations. One of the versatile tools within this library is the numpy.insert() function, which allows for the insertion of values into a Numpy array along a specified axis. This tutorial aims to elucidate this function through a series of examples, starting from basic usage to more advanced applications.

Syntax:

numpy.insert(arr, obj, values, axis=None)

Where:

  • arr: array_like. Input array.
  • obj: int, slice, or sequence of ints. Object that defines the index or indices before which values are inserted.
  • values: array_like. Values to insert into arr. If the type of values is different from that of arr, values is converted to the type of arr.
  • axis: int, optional. Axis along which to insert values. If axis is None, then arr is flattened first.

Example 1: Basic Usage of numpy.insert()

The simplest form of numpy.insert() involves adding a single value into a flat array. Consider a numpy array arr = np.array([1, 3, 5, 7, 9]). To insert the value 2 at the second position, you would use:

import numpy as np
arr = np.array([1, 3, 5, 7, 9])
new_arr = np.insert(arr, 1, 2)
print(new_arr)

Output:

[1, 2, 3, 5, 7, 9]

This operation has shifted the subsequent elements to the right and inserted the value 2 at the specified index.

Example 2: Inserting Multiple Values

You can also insert multiple values into an array. For instance, if you want to include several values at different positions, you can pass a list of indices and values to insert. To demonstrate, let’s expand our initial array by inserting 4 and 6 to get a complete sequence:

import numpy as np

arr = np.array([1, 3, 5, 7, 9])
indices_to_insert = [1, 3]
values_to_insert = [2, 4]
new_arr = np.insert(arr, indices_to_insert, values_to_insert)
print(new_arr)

Output:

[1, 2, 3, 4, 5, 7, 9]

This time, we provided lists both for indices and values, and numpy.insert() has placed each value at its corresponding position, expanding the array accordingly.

Example 3: Advanced: Insertion Along Different Axes

Arrays in Numpy can have more than one dimension. Thus, insertion is not limited to a flat structure. When dealing with multidimensional arrays, you can specify an axis along which to insert values. Consider a 2D array, and you wish to insert a new row:

import numpy as np

arr = np.array([1, 3, 5, 7, 9])

arr_2d = np.array([[1, 2], [5, 6]])
row_to_insert = np.array([3, 4])
new_arr = np.insert(arr_2d, 1, row_to_insert, axis=0)
print(new_arr)

Output:

[[1, 2]
 [3, 4]
 [5, 6]]

By setting axis=0, we instruct Numpy to insert the new row at the specified index. Conversely, to add a column, change the axis to 1:

col_to_insert = np.array([3, 4])
new_arr = np.insert(arr_2d, 1, col_to_insert, axis=1)
print(new_arr)

Output:

[[1, 3, 2]
 [5, 4, 6]]

This flexibility to manipulate both rows and columns makes numpy.insert() incredibly useful for array shaping and transformation in data preprocessing tasks.

Example 4: Conditional Insertion

What about more complex scenarios where insertion depends on certain conditions? Numpy doesn’t directly offer conditional insertions via the insert() function, but we can emulate this behavior by first finding the indices where conditions are met, and then applying insertion. For instance, insert 100 into an array wherever its values are below 50:

import numpy as np

arr = np.array([20, 60, 40, 80])
indices_to_insert = np.where(arr < 50)[0]
# Since multiple values are being inserted at potentially the same index, adjust indices accordingly
adjusted_indices = indices_to_insert + np.arange(len(indices_to_insert))
new_arr = np.insert(arr, adjusted_indices, 100)
print(new_arr)

Output:

[100, 20, 60, 100, 40, 80]

This complex example not only demonstrates conditional insertion but also highlights managing multiple insertions where index adjustment is mandatory to maintain coherency in the resulting array.

Conclusion

Through this guide, we’ve explored the numpy.insert() function across a range of scenarios, from simple value addition to conditional and axis-specific insertions. Mastering this function undeniably enhances your data manipulation capabilities in Numpy, paving the way for more efficient data preprocessing and array transformations in your Python projects.