Python / Numpy - 从子集获取索引到主数组 [英] Python/Numpy - Get Index into Main Array from Subset
问题描述
假设我有一个100元素的numpy数组。我对这个数组的一个子集执行一些计算 - 可能有20个元素满足某些条件。然后我在这个子集中选择一个索引,如何(有效地)恢复第一个数组中的索引?我不想对a中的所有值执行计算,因为它很昂贵,所以我只想在需要的地方执行它(满足条件的地方)。
Say I have a 100 element numpy array. I perform some calculation on a subset of this array - maybe 20 elements where some condition is met. Then I pick an index in this subset, how can I (efficiently) recover the index in the first array? I don't want to perform the calculation on all values in a because it is expensive, so I only want to perform it where it is required (where that condition is met).
这是一些伪代码来证明我的意思(这里的'条件'是列表理解):
Here is some pseudocode to demonstrate what I mean (the 'condition' here is the list comprehension):
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
编辑:
我不是很清楚,所以我提供了一个更完整的例子。我希望这能让我更明确地了解自己的目标。我觉得有一些聪明有效的方法可以做到这一点,没有一些循环或查找。
I wasn't being very clear, so I've provided a more full example. I hope this makes it more clear about what my goal is. I feel like there is some clever and efficient way to do this, without some loops or lookups.
代码:
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.
推荐答案
我不确定我是否理解你的问题。所以,如果我错了,请纠正我。
I am not sure if I understand your question. So, correct me if I am wrong.
假设你有类似的东西
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]
或者如果你不想使用面具:
Or if you don't want to work with masks:
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 - 从子集获取索引到主数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!