我有numpy矩阵X = np.matrix([[1, 2], [3, 4], [5, 6]])
和y = np.matrix([1, 1, 0])
,我想基于y矩阵创建两个新的矩阵X_pos和X_neg。所以希望我的输出结果如下:X_pos == matrix([[1, 2], [3, 4]])
和X_neg == matrix([[5, 6]])
。我怎么能这样做?
答案 0 :(得分:1)
如果你愿意用y
创建一个布尔掩码,这就变得很简单了。
mask = np.array(y).astype(bool).reshape(-1,)
X_pos = X[mask, :]
X_neg = X[~mask, :]
print(X_pos)
matrix([[1, 2],
[3, 4]])
print(X_neg)
matrix([[5, 6]])
答案 1 :(得分:1)
使用np.ma.masked_where例程:
x = np.matrix([[1, 2], [3, 4], [5, 6]])
y = np.array([1, 1, 0])
m = np.ma.masked_where(y > 0, y) # mask for the values greater than 0
x_pos = x[m.mask] # applying masking
x_neg = x[~m.mask] # negation of the initial mask
print(x_pos)
print(x_neg)