簡體   English   中英

使用數組操作過濾numpy

[英]Filtering numpy using array operations

我正在使用python並嘗試過濾2d數組以僅包括具有一定總和且不包含元素0的數組。

其他教程似乎顯示了如何使用numpy.where過濾數組以獲取滿足條件的某些元素,例如,但是我試圖僅獲取滿足條件的某些數組而不使用循環,而是使用numpy方法。

類似於此操作,但具有數組和numpy:

import itertools

list_o_tuples = list(filter(lambda x: sum(x)==10 and 0 not in x, 
                    itertools.combinations(range(10),3)))
#returns [(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]

我認為這是您想要的:

test = np.array(list(itertools.combinations(range(10),3)))
mask = (test.sum(axis=1) == 10) & (test.all(axis=1))
test[mask]

為了提高安全性/可讀性,您可能需要使用(test != 0).all(axis=1)而不是test.all(axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM