How To Remove Elements From Numpy Array?


How To Remove Elements From Numpy Array?

Table Of Contents:

  1. np.delete( )
  2. Examples Of np.delete() Method.

(1) np.delete( )

  • A copy of arr with the elements specified by obj removed.
  • Note that delete does not occur in-place.
  • If axis is None, out is a flattened array.

Syntax:

numpy.delete(arr, obj, axis=None)

Parameters:

  • arr: array_like Input array.
  • obj: slice, int or array of ints – Indicate indices of sub-arrays to remove along the specified axis.
  • axis: int, optional – The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array.

Returns:

  • out: ndarray A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array.

(2) Examples Of np.delete()

Example-1:

import numpy as np
a = np.array([3,1,5,2,6,3,7,4,1])
np.delete(a,obj=[3])

Output:

array([3, 1, 5, 6, 3, 7, 4, 1])

Note:

  • It will remove the element at index position ‘3’.

Example-2:

arr = np.arange(12) + 1
arr
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
np.delete(arr,obj=[0,2,4], axis=0)

Output:

array([ 2,  4,  6,  7,  8,  9, 10, 11, 12])

Note:

  • It will remove the element at index positions ‘0’, ‘2’, and ‘4’.

Leave a Reply

Your email address will not be published. Required fields are marked *