numpy.all axis parameter misbehavior?

浪子不回头ぞ 提交于 2019-11-30 15:59:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43010072/numpy-all-axis-parameter-misbehavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!