0

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?

2
  • Any particular reason why they are matrices? Commented Sep 2, 2017 at 20:26
  • It's easy for me to work with matrices in my previous and following code. Commented Sep 2, 2017 at 20:28

2 Answers 2

1

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]])
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.