NUMPY equivalent of list.pop?

Is there a NumPy method that is equivalent to the built-in pop for Python lists?

Popping obviously doesn't work with numpy arrays, and I want to avoid list conversion.

+14
source share
3 answers

There is no pop method for NumPy arrays, but you can just use a base slice (which would be effective 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 the pop method existed, it would return the last value to y and modify y .

Above,

 last, y = y[-1], y[:-1] 

assigns the last value to the last variable and changes y .

+11
source

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]]) 
+6
source

Pop does not exist for NumPy arrays, but you can use NumPy indexing in conjunction with array restructuring like hstack / vstack or numpy.delete () to emulate popping.

Here are some examples of functions that I can come up with (which apparently don't work when the index is -1, but you can fix it with a simple conditional):

 def poprow(my_array,pr): """ row popping in numpy arrays Input: my_array - NumPy array, pr: row index to pop out Output: [new_array,popped_row] """ i = pr pop = my_array[i] new_array = np.vstack((my_array[:i],my_array[i+1:])) return [new_array,pop] def popcol(my_array,pc): """ column popping in numpy arrays Input: my_array: NumPy array, pc: column index to pop out Output: [new_array,popped_col] """ i = pc pop = my_array[:,i] new_array = np.hstack((my_array[:,:i],my_array[:,i+1:])) return [new_array,pop] 

This returns an array without a popup row / column, as well as a popup row / column separately:

 >>> A = np.array([[1,2,3],[4,5,6]]) >>> [A,poparow] = poprow(A,0) >>> poparow array([1, 2, 3]) >>> A = np.array([[1,2,3],[4,5,6]]) >>> [A,popacol] = popcol(A,2) >>> popacol array([3, 6]) 
+2
source

All Articles