【问题标题】:Mask zero values in matrix and reconstruct original matrix using indices屏蔽矩阵中的零值并使用索引重建原始矩阵
【发布时间】:2019-10-14 17:39:51
【问题描述】:

如果我们有

indice=[0 0 1 1 0 1]; 

X=[0 0 0;0 0 0;5 8 9;10 11 12; 0 0 0; 20 3 4],

我想用索引屏蔽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; 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解决这个问题吗?

【问题讨论】:

  • 你如何定义indice
  • indice 只是一个具有 0 和 1 值的输入向量
  • 你里面有 5 和 2。更正您的问题
  • 感谢您的评论 :)
  • 您真的需要使用特定的indice 还是可以用其他方式定义它?例如使用np.where ?

标签: python loops numpy matrix


【解决方案1】:

使用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.]])

【讨论】:

  • 谢谢 :D 这是第一部分,以防万一,我们想回到初始维度,我的意思是从 print(X[index]) 到 X=np.array([[0 ,0 ,0 ],[0, 0, 0],[5, 8, 9],[10, 11, 12],[ 0, 0,0],[ 20, 3, 4]])。你知道我们该怎么做吗?
  • 是的。请参阅我的更新答案。请考虑接受我的回答
猜你喜欢
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 2020-11-22
  • 2016-08-12
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多