3

I have a following array.

a = np.array([[0, 5, 0, 5],
              [0, 9, 0, 9]])
>>>a.shape 
Out[72]: (2, 4)

>>>np.all(a,axis=0)
Out[69]: 
array([False,  True, False,  True], dtype=bool)

>>>np.all(a,axis=1)
Out[70]: 
array([False, False], dtype=bool)

Because axis 0 means the first axis(row-wise) in 2D array,

I expected when np.all(a,axis=0) is given, it checks whether all element is True or not, per every row.

But it seems like checking per column cause it gives output as 4 elements like array([False, True, False, True], dtype=bool).

What am I misunderstanding about np.all functioning?

4
  • axis=0 is per col for 2D. The axes start from left as 0,1,2, etc. Commented Mar 24, 2017 at 22:22
  • I remember seeing a good duplicate for this, but I can't find it. Commented Mar 24, 2017 at 22:25
  • 1
    Think of the axis argument as the the axis you are collapsing. When you pass axis=0, you are collapsing all of the rows, to one row. Commented Mar 24, 2017 at 22:26
  • stackoverflow.com/questions/41733479/… - meaning of 'sum along axis' explained. Commented Mar 24, 2017 at 22:50

1 Answer 1

3

axis=0 means to AND the elements together along axis 0, so a[0, 0] gets ANDed with a[1, 0], a[0, 1] gets ANDed with a[1, 1], etc. The axis specified gets collapsed.

You're probably thinking that it takes np.all(a[0]), np.all(a[1]), etc., selecting subarrays by indexing along axis 0 and performing np.all on each subarray. That's the opposite of how it works; that would collapse every axis but the one specified.

With 2D arrays, there isn't much advantage for one convention over the other, but with 3D and higher, NumPy's chosen convention is much more useful.

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

1 Comment

um, it's a bit of late though, but thanks anyway!. I finally understood this.!

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.