1

I have:

import numpy as np

a = np.array([[1,1,1],[-1,-1,-1]])

print (a)

Output:

[[ 1  1  1]
 [-1 -1 -1]]

I can do:

b = np.where(np.mean(a,axis=1) > 0,1,0)

print (b)

Which correctly results in:

[1 0]

But when I do:

b = np.where(np.mean(a,axis=1) > 0,np.array([1,1]),np.array([0,0]))

print (b)

It results in the same:

[1 0]

What I want is:

[[1 1]
 [0 0]]

In verbose, I want to replace elements of ndarray based on mean along axis 1 with array and not single integer. So the output from a 2D array should be a 2D array.

5
  • Do you mean [[ 1 1] [0 0]] as output? Commented May 2, 2021 at 17:04
  • Yes sorry. I corrected Commented May 2, 2021 at 17:08
  • What is this doing in verbose? Commented May 2, 2021 at 17:08
  • why not just replace 1 with [1, 1] 0 with [0, 0]. value array need to be the same shape with condition array Commented May 2, 2021 at 17:10
  • If you mean np.where(randn.mean(axis=0) > 0,[1,0],[1,0]) that neither works. In fact I want to generate labels from a 2D array. So axis 0 will have a the same length but axis 1 must be different after the operation. Commented May 2, 2021 at 17:12

1 Answer 1

2
In [254]: np.mean(a,axis=1) > 0,np.array([1,1]),np.array([0,0])
Out[254]: (array([ True, False]), array([1, 1]), array([0, 0]))

The 3 arguments are (2,) shaped arrays. They broadcast against each other to return a (2,) array.

The key is, broadcasting. It is picking elements from the 2 arrays based on corresponding elements of the condition. It is't a wholesale pick between the two.

If the condition is (2,1) shaped, that will broadcast against the (2,) to produce a (2,2) result

In [255]: (np.mean(a,axis=1) > 0)[:,None],np.array([1,1]),np.array([0,0])
Out[255]: 
(array([[ True],
        [False]]),
 array([1, 1]),
 array([0, 0]))

In [256]: np.where((np.mean(a,axis=1) > 0)[:,None],np.array([1,1]),np.array([0,0]))
Out[256]: 
array([[1, 1],
       [0, 0]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the trick / great explanation!

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.