如果我们有
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],
我想用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; 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解决吗?
答案 0 :(得分:0)
使用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.]])