mike
mike

Reputation: 37

Subsetting a NumPy matrix using another matrix

I have numpy matrices X = np.matrix([[1, 2], [3, 4], [5, 6]]) and y = np.matrix([1, 1, 0]) and I want to create two new matrices X_pos and X_neg based on y matrix. So hope my output will be the following: X_pos == matrix([[1, 2], [3, 4]]) and X_neg == matrix([[5, 6]]). How can I do this?

Upvotes: 0

Views: 60

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

With np.ma.masked_where routine:

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)

Upvotes: 1

cs95
cs95

Reputation: 403130

If you're willing to create a boolean mask out of y, this becomes simple.

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]])

Upvotes: 1

Related Questions