gpt4 book ai didi

Python/Numpy - 从子集中获取主数组的索引

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

假设我有一个 100 元素的 numpy 数组。我对这个数组的一个子集执行了一些计算——可能是满足某些条件的 20 个元素。然后我在这个子集中选择一个索引,我怎样才能(有效地)恢复第一个数组中的索引?我不想对 a 中的所有值执行计算,因为它很昂贵,所以我只想在需要的地方(满足该条件的地方)执行它。

这是一些伪代码来证明我的意思(这里的“条件”是列表理解):

a = np.arange(100)                                 # size = 100
b = some_function(a[[i for i in range(0,100,5)]]) # size = 20
Index = np.argmax(b)

# Index gives the index of the maximum value in b,
# but what I really want is the index of the element
# in a

编辑:

我不是很清楚,所以我提供了一个更完整的例子。我希望这能让我更清楚我的目标是什么。我觉得有一些聪明而有效的方法可以做到这一点,而无需一些循环或查找。

代码:

import numpy as np

def some_function(arr):
return arr*2.0

a = np.arange(100)*2. # size = 100
b = some_function(a[[i for i in range(0,100,5)]]) # size = 20
Index = np.argmax(b)

print Index
# Index gives the index of the maximum value in b, but what I really want is
# the index of the element in a

# In this specific case, Index will be 19. So b[19] is the largest value
# in b. Now, what I REALLY want is the index in a. In this case, that would
# 95 because some_function(a[95]) is what made the largest value in b.
print b[Index]
print some_function(a[95])

# It is important to note that I do NOT want to change a. I will perform
# several calculations on SOME values of a, then return the indices of 'a' where
# all calculations meet some condition.

最佳答案

我不确定我是否理解你的问题。所以,如果我错了,请纠正我。

假设你有类似的东西

a = np.arange(100)
condition = (a % 5 == 0) & (a % 7 == 0)
b = a[condition]
index = np.argmax(b)
# The following should do what you want
a[condition][index]

或者如果您不想使用 mask :

a = np.arange(100)
b_indices = np.where(a % 5 == 0)
b = a[b_indices]
index = np.argmax(b)
# Get the value of 'a' corresponding to 'index'
a[b_indices][index]

这是你想要的吗?

关于Python/Numpy - 从子集中获取主数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5761642/

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