![](/img/trans.png)
[英]numpy.where on 2D array is slower than list comprehensino of numpy.where on 1D array
[英]Searching 2D array with numpy.where with multiple conditions
我有一個二維數組,定義如下:
traces = [['x1',11026,0,0,0,0],
['x0',11087,0,0,0,1],
['x0',11088,0,0,1,3],
['x0',11088,0,0,0,3],
['x0',11088,0,1,0,1]]
我想找到與所選列的多個條件匹配的行的索引。 例如,我想在此數組中找到行
row[0]=='x0' & row[1]==11088 & row[3]==1 & row[5]=1
搜索此條件應返回4。
我試圖使用numpy.where,但似乎無法使其在多種條件下工作
print np.where((traces[:,0] == 'x0') & (traces[:,1] == 11088) & (traces[:,3] == 1) & (traces[:,5] == 1))
以上創建警告
FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison print np.where((traces[:,0] == 'x0') & (traces[:,1] == 11088) & (traces[:,3]
== 1) & (traces[:,5] == 1)) (array([], dtype=int32),)
我也嘗試使用numpy.logical_and
,而且創建類似的警告似乎也不起作用。
我有什么辦法可以使用numpy.where
而無需遍歷整個2D數組?
謝謝
魔術水晶球說,問題與陣列的構造有關。
traces = [['x1',11026,0,0,0,0],
['x0',11087,0,0,0,1],
['x0',11088,0,0,1,3],
['x0',11088,0,0,0,3],
['x0',11088,0,1,0,1]]
traces = np.array(traces)
這表現出所描述的錯誤。 通過打印結果數組可以看出原因:
print(traces)
# array([['x1', '11026', '0', '0', '0', '0'],
# ['x0', '11087', '0', '0', '0', '1'],
# ['x0', '11088', '0', '0', '1', '3'],
# ['x0', '11088', '0', '0', '0', '3'],
# ['x0', '11088', '0', '1', '0', '1']],
# dtype='<U5')
數字已轉換為字符串!
作為解決方案,將數組顯式構造為“對象數組”:
traces = np.array(traces, dtype='object')
print(np.where((traces[:,0] == 'x0') & (traces[:,1] == 11088) & (traces[:,3] == 1) & (traces[:,5] == 1)))
# (array([4], dtype=int32),)
請注意,盡管這可行,但是使用對象數組通常不是一個好主意。 可以考慮用數字值替換第一列中的字符串。
考慮一下此比較:
>>> traces[:,[0,1,3,5]] == ['x0', 11088, 1, 1]
array([[False, False, False, False],
[ True, False, False, True],
[ True, True, False, False],
[ True, True, False, False],
[ True, True, True, True]])
我們正在尋找一個(或多個)所有值都等於True的行:
>>> np.where(np.all(traces[:,[0,1,3,5]] == ['x0', 11088, 1, 1], axis=1))
(array([4]),)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.