python numpy array索引_Python / Numpy - 从子集获取索引到主数组

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

EDIT:

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.

CODE:

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.

Let's say you have something like

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]

Is this what you want?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值