Python 删除numpy数组的空维度
我有一个形状(X,Y,Z)的numpy数组。我想检查每个Z维度并快速删除非零维度 详细说明: 我想检查数组[:,:,0]是否有非零项 如果是,则忽略并检查数组[:,:,1]Python 删除numpy数组的空维度,python,python-3.x,numpy,Python,Python 3.x,Numpy,我有一个形状(X,Y,Z)的numpy数组。我想检查每个Z维度并快速删除非零维度 详细说明: 我想检查数组[:,:,0]是否有非零项 如果是,则忽略并检查数组[:,:,1] 否则,如果没有,请删除维度数组[:,:,0]我不确定您想要什么,但希望这指向了正确的方向 编辑1月1日: 受@J.Warren使用np.squence的启发,我认为np.compress可能更合适 这在一行中完成压缩 np.compress((a!=0).sum(axis=(0,1)), a, axis=2) # 解释n
否则,如果没有,请删除维度数组[:,:,0]我不确定您想要什么,但希望这指向了正确的方向 编辑1月1日:
受@J.Warren使用np.squence的启发,我认为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
我可能不再相关的第一个答案
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]]])
也不是100%确定你的目标,但我认为你想要的
np.squeeze(array, axis=2)