Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy-equivalent of list.pop?

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.

like image 311
Anton Alice Avatar asked Oct 09 '16 15:10

Anton Alice


People also ask

How do I remove an element from a NumPy array?

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.

How do you use the pop method in Python?

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.


2 Answers

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.

like image 52
unutbu Avatar answered Oct 04 '22 06:10

unutbu


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]]) 
like image 33
mozlingyu Avatar answered Oct 04 '22 06:10

mozlingyu