[英]How to get index of non-zero item in an array and use this index to get another value from another array or list
我有一個項目,其中您必須 select 數組中的非零項並獲取其索引。 使用此索引,您必須在另一個數組或列表中找到其對應的值。
例如:
best_chr = [[1 1 0]] # numpy array
activity = [2, 3, 4]
代碼如下所示:
chosen_act = [activity[item] for item in range(len(best_chr)) if item != 0]
print(chosen_act)
我打算做的是在best_chr
[1, 1 for the example above] 中找到non-zero
項/值的index
。 然后,使用這個索引,在activity
中找到它的對應值。
Expected output:
chosen_act = [2, 3]
問題是,使用上面的代碼,我收到以下錯誤:
TypeError: object of type 'numpy.int32' has no len()
任何幫助,將不勝感激! 謝謝!
您可以只使用zip
:
# best_chr.flatten since it looks like 2-d array
[i for i, j in zip(activity, best_chr.flatten()) if j]
如果需要使用索引,請使用numpy.flatnonzero
:
[activity[i] for i in np.flatnonzero(best_chr)]
Output:
[2, 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.