高级切片:给定索引列表,从numpy数组中选取不同的元素

2024-04-20 10:12:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在实现一个决策算法。在daily_choices数组中,每天有两种水果可供选择,例如:

daily_choices = np.array([['apple','orange'],['strawberry','orange'],['watermelon','apple']])

现在我有一张单子,上面有我每天要选的水果:

decision = [0,1,0] 

我知道一些基本的切片,比如daily_choices[:,0],意思是把第一列切片出来,daily_choices[:,1]意思是把第二列切片出来。你知道吗

我想知道是否有任何方法可以像下面这样将第一行中的第一列、第二行中的第二列、第三行中的第一列进行切片

预期结果

Input  =>  daily_choices[:,[0,1,0]]
Output =>  ['apple', 'orange', 'watermelon']

然而,它并没有给我想要的结果

我知道我可以通过使用ziploop达到我想要的结果

daily_decision
daily_decision = []
for choices, index in zip(daily_choices, decision):
    daily_decision.append(choices[index])
daily_decision

但我想知道是否有可能在一条线上完成。你知道吗


Tags: 算法appleindexnp切片数组ziparray
2条回答

使用列表理解

choices = [['apple', 'orange'], ['strawberry', 'orange'], ['watermelon', 'apple']]
decisions = [0, 1, 0] 

daily_decisions = [day[decision] for day, decision in zip(choices, decision)]
print(daily_decisions)

['apple', 'orange', 'watermelon']

使用numpy

这也可以用NumPys Integer Array Indexing来解决:

import numpy as np
daily_choices = np.array([['apple','orange'],['strawberry','orange'],['watermelon','apple']])
decisions = [0, 1, 0]

daily_decision = daily_choices[range(len(daily_choices)), decisions]
print(daily_decision)

['apple', 'orange', 'watermelon']

纯粹使用numpy

import numpy as np

daily_choices = np.array([['apple', 'orange'],['strawberry', 'orange'],['watermelon', 'apple']])
decision = np.array([0, 1, 0])

n_fruits = 2

fruit_range = np.reshape(np.arange(n_fruits), (-1, n_fruits))
indices = np.reshape(decision, (len(decision), 1)) == fruit_range

daily_choices[indices]

输出:

array(['apple', 'orange', 'watermelon'], dtype='<U10')

相关问题 更多 >