我有一个numpy数组y [1,2,3,4,5,6,1,2,3,4,5,6]
然后我有一个numpy csr格式的矩阵X.
1)我需要在y中屏蔽元素6。然后,我需要屏蔽X中的相应行。
所以,y.shape是12.应该是10.X是12,20。应该是10,20。
如何在numpy
中执行此操作答案 0 :(得分:1)
如果您的'蒙面'输出y
应该小于您的输入,那么您实际上并没有使用蒙版。
根据previous question的建议,您可以轻松找到y
与6不同的指数
condition = (y != 6)
可以用来检索非{6}的y
值的abool数组
y = y[condition]
您可以使用相同的condition
来获取X
的相应行,但它是CSR,因此不支持花哨的索引格式。你仍然可以将它转换为LIL然后再回来。
您还可以获取y !=6
与
(indices,) = np.nonzero(y != 6)
这是一个常规整数数组,可用于索引X
。
答案 1 :(得分:1)
我不喜欢回答我自己的问题,但正确的解决办法是处理csr矩阵:
X = X[np.where(y != 6)[0]]
y = y[y != 6]
答案 2 :(得分:0)
我不是100%确定我理解你的问题,但也许这会有所帮助:
>>> import numpy as np
>>> a = np.array(range(1,7)*2) #Your array.
>>> a
array([1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6])
>>> b = np.array(list(a)*20).reshape(12,20) #just some matrix of right size and shape. np.empty(12,20) would probably work just as well.
>>> b
array([[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
[5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
[5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
[5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
[5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]])
>>> mask = a != 6 #mask. True for all points except ones where value == 6.
>>> b[mask,:] #take points along first axis where mask==True, all points along second axis.
array([[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
[5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4],
[5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2],
[3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4]])
答案 3 :(得分:0)
使用nonzero。
(假设已经定义了x)
import numpy as np
y = np.array([1,2,3,4,5,6,1,2,3,4,5,6])
keepers = np.nonzero(y != 6)
y = y[keepers]
x = x[keepers, :]