python - 从数组中删除所有零
问题描述
我有一个形状为 [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)
编辑
评论中的所有解决方案都有效,但我给我用过的那个打了绿色勾号。谢谢大家。
解决方案
不要使用 for 循环——那些很慢。在 for 循环中重复调用np.delete
是导致性能下降的秘诀。
相反,创建一个掩码:
zero_rows = (points == 0).all(1)
这是一个长度为 120000 的数组,它是 True ,其中该行中的所有元素都是 0。
然后找到第一个这样的行:
first_invalid = np.where(zero_rows)[0][0]
最后,对数组进行切片:
points[:first_invalid]
推荐阅读
- javascript - 承诺更新 DOM 后如何获得钩子
- javascript - 我们如何在不请求许可的情况下获取用户的当前位置/城市?
- sql - 如何获得员工职能的首要地位?
- java - ArrayList 是否实现了 List ADT 的行为?
- javascript - JQuery 3.3.0 slideDown() Mobile Jumpback to display none
- android - 依赖冲突问题:Here-SDK.aar 和 Directions-api.aar 文件重复类
- sql - 在 Athena AWS 上,表上的最后更新?
- node.js - 如何用 node js 定义路由?
- firebase - 获取文档 ID 包含我的字符串的所有文档
- hangfire - 如何获取我的重复工作列表?