Is there a numpy method which is equivalent to the builtin pop
for python lists?
Popping obviously doesn't work on numpy arrays, and I want to avoid a list conversion.
To remove an element from a NumPy array: Specify the index of the element to remove. Call the numpy. delete() function on the array for the given index.
Example: Use Pop In Python to Remove an Item and Return It In this code, you will create a list of fruits and then use the Python list pop() function to remove an item at a specified index. You will then store the returned value in a variable and print it to see what the pop() function returns.
There is no pop
method for NumPy arrays, but you could just use basic slicing (which would be efficient since it returns a view, not a copy):
In [104]: y = np.arange(5); y Out[105]: array([0, 1, 2, 3, 4]) In [106]: last, y = y[-1], y[:-1] In [107]: last, y Out[107]: (4, array([0, 1, 2, 3]))
If there were a pop
method it would return the last
value in y
and modify y
.
Above,
last, y = y[-1], y[:-1]
assigns the last value to the variable last
and modifies y
.
Here is one example using numpy.delete()
:
import numpy as np arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) print(arr) # array([[ 1, 2, 3, 4], # [ 5, 6, 7, 8], # [ 9, 10, 11, 12]]) arr = np.delete(arr, 1, 0) print(arr) # array([[ 1, 2, 3, 4], # [ 9, 10, 11, 12]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With