我有一个形状为(X,Y,Z)的 numpy 数组。我想要非常快地检查每个 Z 维度并删除非零维度。
详细解释:
我想要检查 array[:,:,0] 是否有任何非零条目。
如果是,则忽略并检查 array[:,:,1]。
否则,删除维度 array[:,:,0]。
详细解释:
我想要检查 array[:,:,0] 是否有任何非零条目。
如果是,则忽略并检查 array[:,:,1]。
否则,删除维度 array[:,:,0]。
np.squeeze(array, axis=2)
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.squeeze.html
我不确定你想要什么,但希望这可以指引你正确的方向。
1月1日编辑:
受@J.Warren使用np.squeeze的启发,我认为np.compress可能更合适。
这一行代码实现了压缩。
np.compress((a!=0).sum(axis=(0,1)), a, axis=2) #
(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]]])
np.squeeze(your_array)
或者your_array.squeeze()
- industArkarray.squeeze(axis=2)
的语法。 - J.Warren