Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy insert() Function



The Numpy insert() function is used to insert values along a specified axis of an array. It takes an array, an index or indices and values to be inserted as its main parameters.

The axis parameter specifies the axis along which to insert the values. If axis is not specified then the array is flattened before the insertion.

This function returns a new array with the inserted values by leaving the original array unchanged.

Syntax

Following is the syntax of Numpy insert() function −

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

Parameters

Following are the parameters of Numpy insert() function −

  • arr: Input array.
  • obj: The index before which insertion is to be made.
  • values: The array of values to be inserted.
  • axis: The axis along which to insert. If not given then the input array is flattened.

Example 1

Following is the basic example of Numpy insert() function, in which the axis parameter is not passed so that the flattened array will be generated −

import numpy as np

# Define the initial array
a = np.array([[1, 2], [3, 4], [5, 6]])

print('First array:')
print(a)
print('\n')

# Insert without axis parameter (flattening the array)
print('Axis parameter not passed. The input array is flattened before insertion.')
print(np.insert(a, 3, [11, 12]))
print('\n')

Output

First array:
[[1 2]
 [3 4]
 [5 6]]


Axis parameter not passed. The input array is flattened before insertion.
[ 1  2  3 11 12  4  5  6]

Example 2

Here in this example we are passing the axis parameter to the insert() function and broadcast to match the input array −

import numpy as np

# Define the initial array
b = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) 

print('First array:')
print(b)
print('\n')

print('Axis parameter passed. The values array is broadcast to match input array.')

# Insert with axis parameter (broadcasting the values)
# Broadcast along axis 0 (inserting rows)
print('Broadcast along axis 0:')
print(np.insert(b, 1, [11, 12], axis=0))
print('\n')

# Broadcast along axis 1 (inserting columns)
print('Broadcast along axis 1:')
print(np.insert(b, 1, 11, axis=1))

Output

First array:
[[1 2]
 [3 4]
 [5 6]
 [7 8]]


Axis parameter passed. The values array is broadcast to match input array.
Broadcast along axis 0:
[[ 1  2]
 [11 12]
 [ 3  4]
 [ 5  6]
 [ 7  8]]


Broadcast along axis 1:
[[ 1 11  2]
 [ 3 11  4]
 [ 5 11  6]
 [ 7 11  8]]
numpy_array_manipulation.htm
Advertisements