删除NumPy数组的空维度

5
我有一个形状为(X,Y,Z)的 numpy 数组。我想要非常快地检查每个 Z 维度并删除非零维度。
详细解释:
我想要检查 array[:,:,0] 是否有任何非零条目。
如果是,则忽略并检查 array[:,:,1]。
否则,删除维度 array[:,:,0]。
2个回答

9

2
不需要为空维度指定轴,它会自动找到。 使用它有两种方法: np.squeeze(your_array) 或者 your_array.squeeze() - industArk
虽然我认为问题只是想检查特定的维度/轴,但这是正确的。不过,我更喜欢array.squeeze(axis=2)的语法。 - J.Warren

5

我不确定你想要什么,但希望这可以指引你正确的方向。

1月1日编辑:
受@J.Warren使用np.squeeze的启发,我认为np.compress可能更合适。

这一行代码实现了压缩。

np.compress((a!=0).sum(axis=(0,1)), a, axis=2) # 

解释 np.compress 中的第一个参数。
(a!=0).sum(axis=(0, 1)) # sum across both the 0th and 1st axes. 
Out[37]: array([1, 1, 0, 0, 2])  # Keep the slices where the array !=0

我的第一个答案可能已经不再相关

(该句话与IT技术无关,只是一句话而已)
import numpy as np

a=np.random.randint(2, size=(3,4,5))*np.random.randint(2, size=(3,4,5))*np.random.randint(2, size=(3,4,5))
# Make a an array of mainly zeroes.
a
Out[31]:
array([[[0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]],

       [[0, 1, 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, 1],
        [0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0]]])

res=np.zeros(a.shape[2], dtype=np.bool)
for ix in range(a.shape[2]):
    res[ix] = (a[...,ix]!=0).any()

res
Out[34]: array([ True,  True, False, False,  True], dtype=bool)
# res is a boolean array of which slices of 'a' contain nonzero data

a[...,res]
# use this array to index a
# The output contains the nonzero slices
Out[35]:
array([[[0, 0, 0],
        [0, 0, 1],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 1, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 1],
        [0, 0, 0],
        [1, 0, 0]]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接