Index a 2D Numpy array with 2 lists of indices

后端 未结 4 566
感动是毒
感动是毒 2020-11-22 12:27

I\'ve got a strange situation.

I have a 2D Numpy array, x:

x = np.random.random_integers(0,5,(20,8))

And I have 2 indexers--one w

4条回答
  •  心在旅途
    2020-11-22 12:52

    import numpy as np
    x = np.random.random_integers(0,5,(4,4))
    x
    array([[5, 3, 3, 2],
           [4, 3, 0, 0],
           [1, 4, 5, 3],
           [0, 4, 3, 4]])
    
    # This indexes the elements 1,1 and 2,2 and 3,3
    indexes = (np.array([1,2,3]),np.array([1,2,3]))
    x[indexes]
    # returns array([3, 5, 4])
    

    Notice that numpy has very different rules depending on what kind of indexes you use. So indexing several elements should be by a tuple of np.ndarray (see indexing manual).

    So you need only to convert your list to np.ndarray and it should work as expected.

提交回复
热议问题