gpt4 book ai didi

python - 从 numpy 矩阵中获取项目,索引在数组中

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:21 25 4
gpt4 key购买 nike

我正在尝试将 matlab 代码转换为 python,我遇到了这样的代码:

a=[1 2 3;4 5 6;7 8 9]
b=[1, 4, 8]
a(b)
//output :
ans :
1 4 8

这实际上是从 b 获取索引并执行

a.item(x) #python

我想问的是,有没有办法在 python 中做到这一点?谢谢。 :)

最佳答案

注意:在撰写此答案时,问题中给出的示例是错误的。 a(b) 将导致:

ans =
1 2 6

提供的 MATLAB 代码使用 linear indexing ,它使用列优先顺序,而所述 a.item(x) Python 函数使用行优先顺序。

ind2sub MATLAB 函数可以将线性索引转换为数组索引。一个类似的 numpy 函数是 unravel_index .

让我们看一下下面的示例代码。注意:Python 使用从 0 开始的索引,而 MATLAB 使用从 1 开始的索引。

import numpy as np

a = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
b = np.array([0, 3, 7])

c = a[np.unravel_index(b, a.shape, 'F')]

print(a)
print(b)
print(c)

[[10 20 30]
[40 50 60]
[70 80 90]]

[0 3 7]

[10 20 60]

关于python - 从 numpy 矩阵中获取项目,索引在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56251397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com