unu*_*tbu 12
popNumPy数组没有方法,但你可以使用基本切片(因为它返回视图而不是副本,因此效率很高):
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]))
Run Code Online (Sandbox Code Playgroud)
如果有pop方法,它将返回last值y并修改y.
以上,
last, y = y[-1], y[:-1]
Run Code Online (Sandbox Code Playgroud)
将最后一个值赋给变量last并进行修改y.
小智 6
这是一个使用示例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]])
Run Code Online (Sandbox Code Playgroud)
小智 6
与 List 不同,numpy 数组没有任何pop()方法,您可以尝试以下一些替代方法 -
>>> x = np.array([1,2,3,4,5])
>>> x = x[:-1]; x
>>> [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
delete() 句法 -np.delete(arr, obj, axis=None)
arr:输入数组
obj:要删除的行号或列号
axis:要删除的轴
>>> x = np.array([1,2,3,4,5])
>>> x = x = np.delete(x, len(x)-1, 0)
>>> [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
NumPy 数组不存在 Pop,但您可以将 NumPy 索引与数组重组(例如 hstack/vstack 或 numpy.delete())结合使用来模拟弹出。
以下是我能想到的一些示例函数(当索引为 -1 时显然不起作用,但您可以使用简单的条件来解决此问题):
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]
Run Code Online (Sandbox Code Playgroud)
这将返回没有弹出行/列的数组,以及单独弹出的行/列:
>>> 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])
Run Code Online (Sandbox Code Playgroud)