Home > OS >  Numpy.delete() function not properly deleting element at index
Numpy.delete() function not properly deleting element at index

Time:06-29

I'm facing a simple problem where I have to delete elements from a 2-dimensional NumPy array-like m. When I try to remove an element at a certain index with delete() function, it just doesn't perform the deletion.

import numpy as np

m = np.array([[1], [1], [3]])
np.delete(m, 2)

print(m)

This code is supposed to output [[1], [1]], as it's deleting the element at index 2. But the actual output it gives is the same original array [[1] [1] [3]].

  • Why is this function not working?
  • And how can I solve it without converting the NumPy array to a Python list?

CodePudding user response:

It's because delete function, returns a copy of changed array.
You need to do this:

import numpy as np

m = np.array([[1], [1], [3]])
m = np.delete(m, 2)
print(m)

In according to numpy documentation: Return a new array with sub-arrays along an axis deleted.

CodePudding user response:

Referring numpy documentation for np.delete :-

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.

Correct code is

import numpy as np

m = np.array([[1], [1], [3]])
m = np.delete(m, 2,0)

print(m)

Output:

[[1] [1]]

  • Related