首页 > 解决方案 > 从数组中删除所有零

问题描述

我有一个形状为 [120000, 3] 的数组,其中只有前 1500 个元素有用,其他元素为 0。

这里有一个例子

[15.0, 14.0, 13.0]
[11.0, 7.0, 8.0]
[4.0, 1.0, 3.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]
[0.0, 0.0, 0.0]

我必须找到一种方法来删除所有 [0.0, 0.0, 0.0] 的元素。我试图写这个,但它不起作用

for point in points:
        if point[0] == 0.0 and point[1] == 0.0 and point[2] == 0.0:
            np.delete(points, point)

编辑

评论中的所有解决方案都有效,但我给我用过的那个打了绿色勾号。谢谢大家。

标签: pythonarrayspython-2.7numpy

解决方案


不要使用 for 循环——那些很慢。在 for 循环中重复调用np.delete是导致性能下降的秘诀。

相反,创建一个掩码:

zero_rows = (points == 0).all(1)

这是一个长度为 120000 的数组,它是 True ,其中该行中的所有元素都是 0。

然后找到第一个这样的行:

first_invalid = np.where(zero_rows)[0][0]

最后,对数组进行切片:

points[:first_invalid]

推荐阅读