我正在实施一个决策算法。在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']
然而,它并没有给我预期的结果
我知道我可以通过使用zip
和loop
来达到我想要的结果
daily_decision
daily_decision = []
for choices, index in zip(daily_choices, decision):
daily_decision.append(choices[index])
daily_decision
但我想知道是否有可能在一行中完成。
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','西瓜']
这也可以用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','西瓜']
使用纯粹的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')