简体   繁体   中英

numpy: How can I use matrix elements as index?

I have a numpy matrix of integers whose elements represent indices. I would like to create a matrix of the same size whose elements are taken from a list at the respective index.

import numpy as np

matrix = np.array([[0, 1, 1], [2, 0, 1]], dtype=int)
matrix

# array([[0, 1, 1],
#        [2, 0, 1]])

values = [7, 8, 9]

values[matrix]  # gives 'ValueError: can only convert an array of size 1 to a Python scalar'

Expected output:

    # array([[7, 8, 8],
    #        [9, 7, 8]])

How can I do this in numpy?

Ok, I just found out I works as expected when values is also an np.ndarray instead of a list. So this works:

import numpy as np

matrix = np.array([[0, 1, 1], [2, 0, 1]], dtype=int)
matrix

# array([[0, 1, 1],
#        [2, 0, 1]])

values = np.array([7, 8, 9])

values[matrix] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM