Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to delete the specific elements of an numpy array "In-place" in python:

when calling the "np.delete()", I am not interested to define a new variable for the reduced size array. I want to execute the delete on the original numpy array. Any thought?

>>> arr = np.array([[1,2], [5,6], [9,10]])
>>> arr
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2],
       [ 9, 10]])
>>> arr
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])
but I want:
>>> arr
array([[ 1,  2],
       [ 9, 10]])
like image 451
P.J Avatar asked Oct 14 '25 20:10

P.J


2 Answers

NumPy arrays are fixed-size, so there can't be an in-place version of np.delete. Any such function would have to change the array's size.

The closest you can get is reassigning the arr variable:

arr = numpy.delete(arr, 1, 0)
like image 76
user2357112 supports Monica Avatar answered Oct 17 '25 11:10

user2357112 supports Monica


The delete call doesn't modify the original array, it copies it and returns the copy after the deletion is done.

>>> arr1 = np.array([[1,2], [5,6], [9,10]])
>>> arr2 = np.delete(arr, 1, 0)
>>> arr1
array([[ 1,  2],
   [ 5,  6],
   [ 9, 10]])
>>> arr2 
array([[ 1,  2],
   [ 9, 10]])
like image 40
Olian04 Avatar answered Oct 17 '25 11:10

Olian04