NumPy: Insert elements, rows, and columns into an array with np.insert()

Posted: | Tags: Python, NumPy

In NumPy, you can insert elements, rows, or columns into an array (ndarray) using the np.insert() function.

This article describes the following contents.

  • Overview of np.insert()
  • For 1D array
    • Insert elements with np.insert()
    • Replace elements
  • For rows of 2D array
    • Insert rows with np.insert()
    • Add rows to the beginning and end with np.vstack()
    • Replace rows
  • For columns of 2D array
    • Insert columns with np.insert()
    • Add rows to the beginning and end with np.hstack()
    • Replace columns

See the following article on how to concatenate multiple arrays.

Overview of np.insert()

The arguments for the np.insert() function are as follows:

  • arr: The original array
  • obj: The position to insert value, can be int, slice, or list
  • value: The value of the element, row, or column to insert
  • axis: The axis along which to insert value

The original array remains unchanged, and a new array is returned.

Insert elements into a 1D array with np.insert()

For 1D arrays, set the axis argument of np.insert() to None. It can be omitted since the default value is None.

import numpy as np

a = np.arange(4)
print(a)
# [0 1 2 3]

print(np.insert(a, 2, 100))
# [  0   1 100   2   3]

print(np.insert(a, 1, [100, 101, 102]))
# [  0 100 101 102   1   2   3]

print(np.insert(a, [0, 2, 4], [100, 101, 102]))
# [100   0   1 101   2   3 102]

Replace elements in a 1D array

To replace elements in a 1D array, follow the example below:

_a = a.copy()
_a[1] = 100
print(_a)
# [  0 100   2   3]

_a = a.copy()
_a[1:3] = [100, 101]
print(_a)
# [  0 100 101   3]

Operations that change the shape of the array before and after replacement will result in an error. For example, replacing one element with multiple elements is not allowed.

# _a = a.copy()
# _a[1] = [100, 101, 102]
# print(_a)
# ValueError: setting an array element with a sequence.

To get the desired array, first use np.insert() to insert the elements, and then use np.delete() to remove unnecessary values.

_a = np.insert(a, 1, [100, 101, 102])
_a = np.delete(_a, 4)
print(_a)
# [  0 100 101 102   2   3]

Insert rows into a 2D array with np.insert()

If you set the axis argument to None (default), the returned array will be flattened, even if the original array is multidimensional.

a = np.arange(12).reshape((3, 4))
print(a)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

print(np.insert(a, 2, 100))
# [  0   1 100   2   3   4   5   6   7   8   9  10  11]

To insert a row into a 2D array, set axis=0.

If you specify a scalar value for the value argument, a row filled with that value will be inserted.

print(np.insert(a, 2, 100, axis=0))
# [[  0   1   2   3]
#  [  4   5   6   7]
#  [100 100 100 100]
#  [  8   9  10  11]]

Insert a 1D array as a row

You can insert a 1D array or a list with the same number of elements as the original array's number of columns.

When specifying the insertion position with the obj argument as a list or an array, the given array will be inserted at the specified positions for each row.

b1 = np.arange(100, 104)
print(b1)
# [100 101 102 103]

print(np.insert(a, 1, b1, axis=0))
# [[  0   1   2   3]
#  [100 101 102 103]
#  [  4   5   6   7]
#  [  8   9  10  11]]

print(np.insert(a, 3, b1, axis=0))
# [[  0   1   2   3]
#  [  4   5   6   7]
#  [  8   9  10  11]
#  [100 101 102 103]]

print(np.insert(a, [0, 2], b1, axis=0))
# [[100 101 102 103]
#  [  0   1   2   3]
#  [  4   5   6   7]
#  [100 101 102 103]
#  [  8   9  10  11]]

Insert a 2D array as a row

You can also insert a 2D array with the same number of columns as the original array.

b2 = np.arange(100, 112).reshape((3, 4))
print(b2)
# [[100 101 102 103]
#  [104 105 106 107]
#  [108 109 110 111]]

print(np.insert(a, 2, b2, axis=0))
# [[  0   1   2   3]
#  [  4   5   6   7]
#  [100 101 102 103]
#  [104 105 106 107]
#  [108 109 110 111]
#  [  8   9  10  11]]

print(np.insert(a, 2, b2[2], axis=0))
# [[  0   1   2   3]
#  [  4   5   6   7]
#  [108 109 110 111]
#  [  8   9  10  11]]

print(np.insert(a, [0, 2, 3], b2, axis=0))
# [[100 101 102 103]
#  [  0   1   2   3]
#  [  4   5   6   7]
#  [104 105 106 107]
#  [  8   9  10  11]
#  [108 109 110 111]]

print(np.insert(a, range(3), b2, axis=0))
# [[100 101 102 103]
#  [  0   1   2   3]
#  [104 105 106 107]
#  [  4   5   6   7]
#  [108 109 110 111]
#  [  8   9  10  11]]

Add rows to the beginning and end of a 2D array with np.vstack()

To add rows to the beginning or end of an array rather than in the middle, use np.vstack() to vertically concatenate arrays.

You can use either a 1D array with the same number of elements as the original array's number of columns or a 2D array with the same number of columns as the original ndarray.

print(np.vstack((a, b1)))
# [[  0   1   2   3]
#  [  4   5   6   7]
#  [  8   9  10  11]
#  [100 101 102 103]]

print(np.vstack((b2, a)))
# [[100 101 102 103]
#  [104 105 106 107]
#  [108 109 110 111]
#  [  0   1   2   3]
#  [  4   5   6   7]
#  [  8   9  10  11]]

Replace rows in a 2D array

To replace rows, follow the example below. The original array is modified.

Both slices and lists are acceptable as long as the number of selected columns is the same.

_a = a.copy()
_a[2] = b1
print(_a)
# [[  0   1   2   3]
#  [  4   5   6   7]
#  [100 101 102 103]]

_a = a.copy()
_a[1] = b2[1]
print(_a)
# [[  0   1   2   3]
#  [104 105 106 107]
#  [  8   9  10  11]]

_a = a.copy()
_a[1:] = b2[[0, 2]]
print(_a)
# [[  0   1   2   3]
#  [100 101 102 103]
#  [108 109 110 111]]

As with 1D arrays, operations that change the shape (number of rows) will result in an error. To get the desired array, first use np.insert() to insert the rows, and then use np.delete() to remove unnecessary rows.

Insert columns into a 2D array with np.insert()

To insert a column into a 2D array, set axis=1. The basic approach is the same as for rows.

print(a)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]

print(np.insert(a, 1, 100, axis=1))
# [[  0 100   1   2   3]
#  [  4 100   5   6   7]
#  [  8 100   9  10  11]]

c1 = np.arange(100, 103)
print(c1)
# [100 101 102]

print(np.insert(a, 1, c1, axis=1))
# [[  0 100   1   2   3]
#  [  4 101   5   6   7]
#  [  8 102   9  10  11]]

print(np.insert(a, 3, c1, axis=1))
# [[  0   1   2 100   3]
#  [  4   5   6 101   7]
#  [  8   9  10 102  11]]

When inserting a 2D array as columns, be careful with the obj argument that specifies the insertion position. To specify a scalar value for obj, use [x] instead of x, otherwise an error will occur.

c2 = np.arange(100, 106).reshape((3, 2))
print(c2)
# [[100 101]
#  [102 103]
#  [104 105]]

# print(np.insert(a, 1, c2, axis=1))
# ValueError: could not broadcast input array from shape (2,3) into shape (3,3)

print(np.insert(a, [1], c2, axis=1))
# [[  0 100 101   1   2   3]
#  [  4 102 103   5   6   7]
#  [  8 104 105   9  10  11]]

print(np.insert(a, [0, 2], c2, axis=1))
# [[100   0   1 101   2   3]
#  [102   4   5 103   6   7]
#  [104   8   9 105  10  11]]

When inserting only one column, the output will differ depending on whether you insert a 1D array or a 2D array. While we won't go into detail here, the result follows broadcasting rules.

Note that if you insert a 1D array with the obj argument set to a list, you may encounter unexpected results.

print(c1)
# [100 101 102]

print(np.insert(a, 1, c1, axis=1))
# [[  0 100   1   2   3]
#  [  4 101   5   6   7]
#  [  8 102   9  10  11]]

print(np.insert(a, [1], c1, axis=1))
# [[  0 100 101 102   1   2   3]
#  [  4 100 101 102   5   6   7]
#  [  8 100 101 102   9  10  11]]

print(np.insert(a, [1, 3, 4], c1, axis=1))
# [[  0 100   1   2 101   3 102]
#  [  4 100   5   6 101   7 102]
#  [  8 100   9  10 101  11 102]]

_c1 = c1.reshape((3, 1))
print(_c1)
# [[100]
#  [101]
#  [102]]

print(np.insert(a, 1, _c1, axis=1))
# [[  0 100 101 102   1   2   3]
#  [  4 100 101 102   5   6   7]
#  [  8 100 101 102   9  10  11]]

print(np.insert(a, [1], _c1, axis=1))
# [[  0 100   1   2   3]
#  [  4 101   5   6   7]
#  [  8 102   9  10  11]]

print(np.insert(a, [1, 3, 4], _c1, axis=1))
# [[  0 100   1   2 100   3 100]
#  [  4 101   5   6 101   7 101]
#  [  8 102   9  10 102  11 102]]

Add columns to the beginning and end of a 2D array with np.hstack()

To add columns to the beginning or end of an array rather than in the middle, you can use np.hstack() to horizontally concatenate arrays.

Note that an error will occur if the number of dimensions of the original array and the array to be added do not match. When adding a single column, ensure it is converted to a 2D array using the reshape() method.

# print(np.hstack((a, c1)))
# ValueError: all the input arrays must have same number of dimensions

print(_c1)
# [[100]
#  [101]
#  [102]]

print(np.hstack((a, _c1)))
# [[  0   1   2   3 100]
#  [  4   5   6   7 101]
#  [  8   9  10  11 102]]

print(np.hstack((_c1, a)))
# [[100   0   1   2   3]
#  [101   4   5   6   7]
#  [102   8   9  10  11]]

print(np.hstack((a, c2)))
# [[  0   1   2   3 100 101]
#  [  4   5   6   7 102 103]
#  [  8   9  10  11 104 105]]

print(np.hstack((c2, a)))
# [[100 101   0   1   2   3]
#  [102 103   4   5   6   7]
#  [104 105   8   9  10  11]]

Replace columns in a 2D array

To replace columns, follow the example below. The original array is modified.

Both slices and lists are acceptable if the number of selected rows is the same.

_a = a.copy()
_a[:, 1] = c1
print(_a)
# [[  0 100   2   3]
#  [  4 101   6   7]
#  [  8 102  10  11]]

_a = a.copy()
_a[:, :2] = c2
print(_a)
# [[100 101   2   3]
#  [102 103   6   7]
#  [104 105  10  11]]

_a = a.copy()
_a[:, [0, 3]] = c2
print(_a)
# [[100   1   2 101]
#  [102   5   6 103]
#  [104   9  10 105]]

As with the previous examples, operations that change the shape (number of columns) will result in an error. To get the desired array, first use np.insert() to insert the columns, and then use np.delete() to remove unnecessary columns.

Related Categories

Related Articles