What is the numpy.delete() Method

Numpy.delete() method “returns a new array with the deletion of sub-arrays along with the mentioned axis.”

Syntax

numpy.delete(array, object, axis = None)

Parameters

The np.delete() function takes three parameters:

  1. array: This is the input array.
  2. object: This can be any single number or a subarray.
  3. axis: This indicates the axis to be deleted from the array.

Return Value

The numpy delete() function returns the array by deleting the subarray, which was mentioned during the function call.

Example 1: How to Use numpy.delete() Method

# Importing numpy
import numpy as np

# We will create an 1D array

# this will create an array with values 0 to 5
arr1 = np.arange(6)
# Printing the array
print("The array is: ", arr1)

# Now we will call delete() function
# To delete the element 3
object = 3 # 3 is to be deleted

# here arr1 is the main array
# object is the number which is to be deleted
arr = np.delete(arr1, object)

# Printing new array
print("After deleting ", object, " new array is: ")
print(arr)

Output

The array is: [0 1 2 3 4 5]
After deleting 3 new array is: 
[0 1 2 4 5]

Example 2: Remove elements from 2D array

We can also remove elements from a 2D array using the numpy delete() function.

# Importing numpy
import numpy as np

# We will create a 2D array
# Of shape 4x3
arr1 = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9), (50, 51, 52)])
# Printing the array
print("The array is: ")
print(arr1)

# Now we will call delete() function
# To delete the subarray present in array

# This indicates this will delete 3rd column
# Of the array
obj = 2 # 3rd column
axis = 1 # column wise

# here arr1 is the main array
# object is the number which is to be deleted
arr = np.delete(arr1, obj, axis)

# Printing new array
print("After deleting column wise new array is: ")
print(arr)

# Now we will delete 2nd row of the array
arr = np.delete(arr, 1, 0)

# Printing new array
print("After deleting row wise new array is: ")
print(arr)

Output

The array is: 
[[ 1 2 3]
 [ 4 5 6]
 [ 7 8 9]
 [50 51 52]]
After deleting column wise new array is: 
[[ 1 2]
 [ 4 5]
 [ 7 8]
 [50 51]]
After deleting row wise new array is: 
[[ 1 2]
 [ 7 8]
 [50 51]]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.