Numpy delete() Function



The Numpy delete() Function is used to return a new array with the specified subarray deleted from the input array. If the axis parameter is not provided then the input array is flattened before deletion.

This function is useful for removing elements, rows or columns from an array.

Syntax

Following is the syntax of Numpy delete() Function −

Numpy.delete(arr, obj, axis)

Parameters

Below are the parameters of the Numpy delete() Function −

  • arr: Input array
  • obj: It can be a slice i.e. an integer or array of integers which indicates the subarray to be deleted from the input array.
  • axis: The axis along which to delete the given subarray. If not given the input array(arr) is flattened.

Example 1

Following is the basic example of Numpy delete() Function which deletes the element at index 5 −

import numpy as np 

# Creating an array with shape (3, 4)
a = np.arange(12).reshape(3, 4)

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

# Delete the element at index 5 from the flattened array
print('Array flattened before delete operation as axis not used:') 
print(np.delete(a, 5)) 

Output

First array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


Array flattened before delete operation as axis not used:
[ 0  1  2  3  4  6  7  8  9 10 11]

Example 2

Here in this example we are deleting a specific column from a 2D array with the help of delete() function −

import numpy as np

# Create a 3x4 array
a = np.arange(12).reshape(3, 4)

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

# Delete the second column (index 1)
result = np.delete(a, 1, axis=1)
print('Array after deleting column 2:')
print(result)

Output

Original array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


Array after deleting column 2:
[[ 0  2  3]
 [ 4  6  7]
 [ 8 10 11]]

Example 3

We can delete multiple elements from an array with the help of slicing. Here in the below example we are passing slicing pattern as the parameter to the delete() function along with the input array −

import numpy as np

# Create a 1D array
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

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

# Delete every second element
result = np.delete(a, np.s_[::2])
print('Array after deleting every second element:')
print(result)

Output

Original array:
[ 1  2  3  4  5  6  7  8  9 10]


Array after deleting every second element:
[ 2  4  6  8 10]
numpy_array_manipulation.htm
Advertisements