问题
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