gpt4 book ai didi

python - numpy:有没有办法从不带外部循环的映射序列创建数组?

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:38 26 4
gpt4 key购买 nike

对我来说,这听起来像是一个常见的用例,但我还找不到适合它的函数/线程。

我有两个 numpy 数组,一个是三元组序列,另一个是关联的索引序列。我想创建一个序列长度相等的一维数组,由根据索引的映射项组成。

例子:

mapping = np.array(((25, 120, 240), (18, 177, 240), (0, 0, 0), (10, 120, 285)))
indices = np.array((0, 1, 0, 0))

print "mapping:", mapping
print "indices:", indices
print "mapped:", mapping[indices]

产生以下输出:

mapping: [[ 25 120 240]
[ 18 177 240]
[ 0 0 0]
[ 10 120 285]]
indices: [0 1 0 0]
mapped: [[ 25 120 240]
[ 18 177 240]
[ 25 120 240]
[ 25 120 240]]

当然,这种方法将整个映射数组作为一个映射,而不是作为映射列表,根据索引数组仅返回第一个或第二个内部映射。但我一直在寻找的是:

mapped: [25 177 0 10]

...由第一个映射的第一项、第二个映射的第二个以及第三个和第四个映射的第一个组成。

有没有一种精简的方法可以单独使用 numpy 功能,无需外部循环,也不会为临时数组占用过多的内存?

最佳答案

我想你在找this part numpy 关于索引的文档。

In [17]: mapping[(np.arange(indices.shape[-1]),indices)]
Out[17]: array([ 25, 177, 0, 10])

这会创建一个临时数组 (np.arange),但它是一维的,我想不出更好的方法。

关于python - numpy:有没有办法从不带外部循环的映射序列创建数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48861733/

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