2

I have an array called A:

A = np.array([[-1, 2, -3],
              [4, -5, 6],
              [-7, 8, -9]])

Now I want to extract positive and negative parts and save them in two new arrays like:

B = np.array([[0, 2, 0],
              [4, 0, 6],
              [0, 8, 0]])

for positive parts and

C = np.array([[-1, 0, -3],
              [0, -5, 0],
              [-7, 0, -9]])

for negative parts.

Could you please guide me how to get arrays B and C from array A in Python 3.6?

1

1 Answer 1

3

The solution

Use two np.wheres to replace the values below zero and above zero:

>>> import numpy as np
>>> A = np.array([[-1, 2, -3], [4, -5, 6], [-7, 8, -9]])
>>> B = np.where(A > 0, A, 0)
>>> C = np.where(A < 0, A, 0)
>>> B
array([[0, 2, 0],
       [4, 0, 6],
       [0, 8, 0]])
>>> C
array([[-1,  0, -3],
       [ 0, -5,  0],
       [-7,  0, -9]])

The explanation

The three argument form of np.where broadcasts the arguments, the first and second already have the same shape (3, 3) but the 0 will be broadcasted to:

>>> Ag0_bc, B_bc, zero_bc = np.broadcast_arrays(A > 0, A, 0)
>>> Ag0_bc
array([[False,  True, False],
       [ True, False,  True],
       [False,  True, False]], dtype=bool)
>>> zero_bc
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Then np.where will create a new array and fill each element in the new array with the corresponding element from the second argument (A) if the element in the first argument (A > 0) is True and take the element from the third argument 0 in case it's False.

Sign up to request clarification or add additional context in comments.

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.