gpt4 book ai didi

python - 将索引操作为 2d numpy 数组

转载 作者:行者123 更新时间:2023-11-28 16:49:16 25 4
gpt4 key购买 nike

我可以用一个元组甚至一个元组列表来索引一个 2d numpy 数组

a = numpy.array([[1,2],[3,4]])
i = [(0,1),(1,0)] # edit: bad example, should have taken [(0,1),(0,1)]
print a[i[0]], a[i]

(给出 2 [2 3])

但是,我不能用向量运算来操作元组,即

k = i[0]+i[1]

不给出所需的 (1,1) 但连接。

另一方面,使用 numpy 数组作为索引,算术有效,但索引无效。

i = numpy.array(i)
k = i[0]+i[1] # ok
print a[k]

给出数组 [[3 4], [3 4]] 而不是所需的 4

有没有办法对索引进行向量运算,同时还能够索引一个numpy数组 与他们一起(不从元组派生类并重载所有运算符)?

This question起初看起来很有希望,但我不知道是否可以将其应用于我的情况。

编辑(对接受的答案发表评论):

...然后处理索引数组也可以使用 map

arr = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
ids = numpy.array([(0,1),(1,0)])
ids += (0,1) # shift all indices by 1 column
print arr[map(tuple,ids.T)]

(虽然让我困惑为什么我需要转置。也会遇到上面这个问题,幸运的是 [(0,1),(0,1)])

最佳答案

是的。需要索引时将 NumPy 数组转换为元组:

a[tuple(k)]

测试:

>>> a = numpy.array([[1,2],[3,4]])
>>> i = numpy.array([(0,1),(1,0)])
>>> k = i[0] + i[1]
>>> a[tuple(k)]
4

关于python - 将索引操作为 2d numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9721193/

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