在不使用for循环的情况下删除numpy数组的前导零

5 python performance numpy python-3.x

如何在不使用循环的情况下仅从numpy数组中删除前导零?

import numpy as np

x = np.array([0,0,1,1,1,1,0,1,0,0])

# Desired output
array([1, 1, 1, 1, 0, 1, 0, 0])
Run Code Online (Sandbox Code Playgroud)

我写了以下代码

x[min(min(np.where(x>=1))):] 
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更有效的解决方案.

Aec*_*lys 5

你可以用np.trim_zeros(x, 'f').

'f'表示从前面修剪零.选项'b'将从后面修剪零.默认选项'fb'从两侧修剪它们.

x = np.array([0,0,1,1,1,1,0,1,0,0])
# [0 0 1 1 1 1 0 1 0 0]
np.trim_zeros(x, 'f')
# [1 1 1 1 0 1 0 0]
Run Code Online (Sandbox Code Playgroud)