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.
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.
There isn't any
pop()
method for numpy arrays unlike List, Here're some alternatives you can try out-delete()
Syntax -
np.delete(arr, obj, axis=None)
arr
: Input arrayobj
: Row or column number to deleteaxis
: Axis to deleteThere 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):If there were a
pop
method it would return thelast
value iny
and modifyy
.Above,
assigns the last value to the variable
last
and modifiesy
.Here is one example using
numpy.delete()
:Pop doesn't exist for NumPy arrays, but you can use NumPy indexing in combination with array restructuring, for example hstack/vstack or numpy.delete(), to emulate popping.
Here are some example functions I can think of (which apparently don't work when the index is -1, but you can fix this with a simple conditional):
This returns the array without the popped row/column, as well as the popped row/column separately: