Python 屏蔽矩阵中的零值,并使用索引重建原始矩阵

Python 屏蔽矩阵中的零值,并使用索引重建原始矩阵,python,loops,numpy,matrix,Python,Loops,Numpy,Matrix,万一我们有 indice=[0 0 1 1 0 1]; 及 我想用indice来屏蔽X中的0值,得到Xx=[5 8 9;10 11 12;20 3 4],然后从Xx返回初始维度newX=[0 0 0;0 0 0;5 8 9;10 11 12;0 0 0 0;20 3 4] for i in range(3): a=X[:,i]; Xx[:,i]=a[indice]; --然后回到初始尺寸: for ii in range(3) aa=Xx[:,ii] bb[i

万一我们有

indice=[0 0 1 1 0 1]; 

我想用indice来屏蔽X中的0值,得到Xx=[5 8 9;10 11 12;20 3 4],然后从Xx返回初始维度
newX=[0 0 0;0 0 0;5 8 9;10 11 12;0 0 0 0;20 3 4]

for i in range(3):
    a=X[:,i];
Xx[:,i]=a[indice]; 
--然后回到初始尺寸:

  for ii in range(3)
    aa=Xx[:,ii]
    bb[indice]=aa
    newX[:,ii]=bb

你能帮我用python解决这个问题吗?

使用
numpy。那里的生活更简单

X=np.array([[0 ,0 ,0],[0, 0, 0],[5, 8, 9],[10, 11, 12],[ 0, 0 ,0],[ 20, 3, 4]])

index = np.where(X.any(axis=1))[0] # find rows with all 0s

print(X[index])
#array([[ 5,  8,  9],
#       [10, 11, 12],
#       [20,  3,  4]])
编辑:

如果确实要重建它,并且基于您知道已删除所有0的行这一事实,那么:

创建包含所有0的新矩阵:

X_new = np.zeros(X.shape)
并在其应位于的位置插入值:

X_new[index] = X[index]
现在检查
X_new

X_new

array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 5.,  8.,  9.],
       [10., 11., 12.],
       [ 0.,  0.,  0.],
       [20.,  3.,  4.]])

使用
numpy.where

X=np.array([[0 ,0 ,0],[0, 0, 0],[5, 8, 9],[10, 11, 12],[ 0, 0 ,0],[ 20, 3, 4]])

index = np.where(X.any(axis=1))[0] # find rows with all 0s

print(X[index])
#array([[ 5,  8,  9],
#       [10, 11, 12],
#       [20,  3,  4]])
编辑:

如果确实要重建它,并且基于您知道已删除所有0的行这一事实,那么:

创建包含所有0的新矩阵:

X_new = np.zeros(X.shape)
并在其应位于的位置插入值:

X_new[index] = X[index]
现在检查
X_new

X_new

array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 5.,  8.,  9.],
       [10., 11., 12.],
       [ 0.,  0.,  0.],
       [20.,  3.,  4.]])

如何定义标记?标记只是一个带有0和1值的输入向量,里面有5和2。更正您的问题谢谢您的评论:)您真的需要使用特定的
标记
,还是可以用另一种方式定义它?e、 g.使用
np.其中
?如何定义
标记
?标记只是一个带有0和1值的输入向量,内部有5和2。更正您的问题谢谢您的评论:)您真的需要使用特定的
标记
,还是可以用另一种方式定义它?e、 使用
np.where
?谢谢:这是第一部分,如果我们想回到初始维度,我的意思是从打印(X[index])到X=np.array([[0,0,0],[0,0,0],[5,8,9],[10,11,12],[0,0,0],[20,3,4])。你知道我们怎么做吗?知道。请参阅我的最新答案。考虑接受我的回答:D,这是第一部分,如果我们想要回到初始维度,我的意思是从打印(x[index ])到x= NP。数组([[ 0, 0, 0 ],[ 0, 0, 0 ],[ 5, 8, 9 ],[ 10, 11, 12 ],[0, 0, 0 ],[20, 3, 4 ] ]。你知道我们怎么做吗?知道。请参阅我的最新答案。请接受我的回答