Access multiple elements of an array

后端 未结 3 2145
心在旅途
心在旅途 2020-12-06 15:08

Is there a way to get array elements in one operation for known rows and columns of those elements? In each row I would like to access elements from col_start to col_end (ea

3条回答
  •  天涯浪人
    2020-12-06 15:44

    You can use np.choose.

    Here's an example NumPy array arr:

    array([[ 0,  1,  2,  3,  4,  5,  6],
           [ 7,  8,  9, 10, 11, 12, 13],
           [14, 15, 16, 17, 18, 19, 20]])
    

    Let's say we want to pick the values [1, 2, 3] from the first row, [11, 12, 13] from the second row and [17, 18, 19] from the third row.

    In other words, we'll pick out the indices from each row of arr as shown in an array idx:

    array([[1, 2, 3],
           [4, 5, 6],
           [3, 4, 5]])
    

    Then using np.choose:

    >>> np.choose(idx, arr.T[:,:,np.newaxis])
    array([[ 1,  2,  3],
           [11, 12, 13],
           [17, 18, 19]])
    

    To explain what just happened: arr.T[:,:,np.newaxis] meant that arr was temporarily viewed as 3D array with shape (7, 3, 1). You can imagine this as 3D array where each column of the original arr is now a 2D column vector with three values. The 3D array looks a bit like this:

    #  0       1       2       3       4       5       6
    [[ 0]   [[ 1]   [[ 2]   [[ 3]   [[ 4]   [[ 5]   [[ 6]   # choose values from 1, 2, 3
     [ 7]    [ 8]    [ 9]    [10]    [11]    [12]    [13]   # choose values from 4, 5, 6
     [14]]   [15]]   [16]]   [17]]   [18]]   [19]]   [20]]  # choose values from 3, 4, 5
    

    To get the zeroth row of the output array, choose selects the zeroth element from the 2D column at index 1, the zeroth element from the 2D column at index 2, and the zeroth element from the 2D column at index 3.

    To get the first row of the output array, choose selects the first element from the 2D column at index 4, the first element from the 2D column at index 5, ... and so on.

提交回复
热议问题