[英]numpy: How can I use matrix elements as index?
I have a numpy matrix of integers whose elements represent indices.我有一个 numpy 整数矩阵,其元素表示索引。 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?我怎样才能在 numpy 中做到这一点?
Ok, I just found out I works as expected when values
is also an np.ndarray
instead of a list.好的,我刚刚发现当values
也是np.ndarray
而不是列表时,我按预期工作。 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.