gpt4 book ai didi

python - 如何从带有索引的二维数组中获取值

转载 作者:行者123 更新时间:2023-11-30 23:26:09 32 4
gpt4 key购买 nike

例如,我有以下二维数组。

>>>np.array(((1,2),(3,4),(5,6))) 
>>>array([[1, 2],
[3, 4],
[5, 6]])

我想从每一列中获取一个元素。例如,我想从第一列获取 3,从第二列获取 6
如何用索引[1,2]来做到这一点。 1 表示第一列中的第二个元素,2 表示第二列中的第三个元素

最佳答案

您可以使用所谓的 fancy indexing 来做到这一点:

In [57]: x = np.array(((1,2),(3,4),(5,6)))

# np.arange(x.shape[1]) gives [0,1], the column indices
# needed to select "one from each column"
In [58]: x[[1,2], np.arange(x.shape[1])]
Out[58]: array([3, 6])
<小时/>

或者您可以使用np.choose :

In [44]: np.choose([1,2], x)
Out[44]: array([3, 6])

关于python - 如何从带有索引的二维数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676374/

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