numpy array indexing: list index and np.array index give different result

后端 未结 2 1591
粉色の甜心
粉色の甜心 2021-01-14 16:53

I am trying to index an np.array using list and np.array indexes. But they give different result.

Here is an illustration:

import numpy         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-14 17:07

    If it's an array it's interpreted as shape of the final array containing the indices - but if it's an list it's the indices along the "dimensions" (multi-dimensional array indices).

    So the first example (with an array) is equivalent to:

    [[x[0], x[1],
     [x[1], x[2]]
    

    But the second example (list) is interpreted as:

    [x[0, 1], x[1, 2]]
    

    But x[0, 1] gives a IndexError: too many indices for array because your x has only one dimension.

    That's because lists are interpreted like it was a tuple, which is identical to passing them in "separately":

    x[[0, 1], [1, 2]]
              ^^^^^^----- indices for the second dimension
      ^^^^^^------------- indices for the first dimension
    

提交回复
热议问题