如何删除numpy数组的前导/尾随零?
import numpy as np
a = np.array([0,0,0,3,2,-1,0,0,7,9,13,0,0,0,0,0,0,0])
#Desired output
[3,2,-1,0,0,7,9,13]
这不起作用:
a[a != 0]
因为它会删除所有零,包括里面的零。
答案 0 :(得分:13)
>>> import numpy as np
>>> a = np.array([0,0,0,3,2,-1,0,0,7,9,13,0,0,0,0,0,0,0])
>>> np.trim_zeros(a)
array([ 3, 2, -1, 0, 0, 7, 9, 13])
答案 1 :(得分:0)
修剪2d数组:
def trim_zeros_2D(array, axis=1):
mask = ~(array==0).all(axis=axis)
inv_mask = mask[::-1]
start_idx = np.argmax(mask == True)
end_idx = len(inv_mask) - np.argmax(inv_mask == True)
if axis:
return array[start_idx:end_idx,:]
else:
return array[:, start_idx:end_idx]
答案 2 :(得分:0)
要修剪二维数组而无需其他功能:
np.array([np.trim_zeros(arr) for arr in array2d])
由数组包装的简单列表理解应该可以正常工作。