Why does indexing numpy arrays with brackets and commas differ in behavior?

后端 未结 3 940
梦如初夏
梦如初夏 2020-11-27 16:42

I tend to index numpy arrays (matrices) with brackets, but I\'ve noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example,

3条回答
  •  旧时难觅i
    2020-11-27 17:13

    This:

    x[:, 1]
    

    means "take all indices of x along the first axis, but only index 1 along the second".

    This:

    x[:][1]
    

    means "take all indices of x along the first axis (so all of x), then take index 1 along the first axis of the result". You're applying the 1 to the wrong axis.

    x[1][2] and x[1, 2] are only equivalent because indexing an array with an integer shifts all remaining axes towards the front of the shape, so the first axis of x[1] is the second axis of x. This doesn't generalize at all; you should almost always use commas instead of multiple indexing steps.

提交回复
热议问题