加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 从N维Numpy数组中仅获取非零子数组

发布时间:2020-12-20 11:04:42 所属栏目:Python 来源:网络整理
导读:我有一个numpy数组’arr’形状(1756020,28,4). 基本上’arr’有1756020个小阵列形状(28,4).在1756020阵列中,967210是“全零”,788810具有所有非零值.我想删除所有967210’全零’小数组.我使用条件arr [i] == 0.any()编写了一个if else循环,但这需要花费很多
我有一个numpy数组’arr’形状(1756020,28,4).
基本上’arr’有1756020个小阵列形状(28,4).在1756020阵列中,967210是“全零”,788810具有所有非零值.我想删除所有967210’全零’小数组.我使用条件arr [i] == 0.any()编写了一个if else循环,但这需要花费很多时间.有没有更好的方法呢?

解决方法

向量化逻辑的一种方法是对包含未测试维度的轴使用带有元组参数的 numpy.any.

# set up 4d array of ones
A = np.ones((5,3,4))

# make second of shape (3,4) = 0
A[1] = 0  # or A[1,...] = 0; or A[1,:,:] = 0

# find out which are non-zero
res = np.any(A,axis=(1,2,3))

print(res)

[True False True True True]

此功能在numpy v0.17向上提供.根据docs:

axis : None or int or tuple of ints,optional

If this is a tuple of ints,a reduction is performed on multiple axes,instead of a single axis or all the axes as before.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读