简体   繁体   中英

Python - construct a matrix by matrix of index

Suppose I have an array, I want to have a matrix from that array by a matrix of index.

import numpy as np
arr = np.array([1,5])
mtxidx = np.array([[0,1,0],[0,1,1],[0,0,0]])

How can I get a matrix [[1,5,1],[1,5,5],[1,1,1]] ?

An initial thought is simply say

arr(mtxidx)

however it doesn't work

Is there any function/method that do this elegantly?

"Fancy" indexing works for me (NB in your question you are trying to call the array object (round brackets) but NumPy "ndarray" objects are not callable):

In [61]: arr[mtxidx]
Out[61]: 
array([[1, 5, 1],
       [1, 5, 5],
       [1, 1, 1]])

Your initial thought was pretty close, simply replacing the parenthesis with [] would make it work. arr[mtxidx]

A list comprehension would work as well.

>>> np.array([arr[row] for row in mtxidx])
array([[1, 5, 1],
       [1, 5, 5],
       [1, 1, 1]])

I upvote the fancy indexing proposed by @xnx but if you would have done something in same range but involving an operation (or ..anything else) you can also try this :

arr = np.array([1,5])
mtxidx = np.array([[0,1,0],[0,1,1],[0,0,0]])

def func(v):
    return arr[v]

vfunc = np.vectorize(func)
vfunc(mtxidx)
# array([[1, 5, 1],
#        [1, 5, 5],
#        [1, 1, 1]])

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