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)
我想知道是否有更有效的解决方案.
你可以用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)
| 归档时间: |
|
| 查看次数: |
495 次 |
| 最近记录: |