[英]Is there a way how i can find the index of an multidimensional numpy array by matching it to another numpy array?
[英]How can I find the index of a tuple inside a numpy array?
我有一個numpy數組:
groups=np.array([('Species1',), ('Species2', 'Species3')], dtype=object)
。
當我問np.where(groups == ('Species2', 'Species3'))
甚至np.where(groups == groups[1])
我得到一個空的回復: (array([], dtype=int64),)
為什么這樣,我如何獲得這樣一個元素的索引?
是的你可以搜索它,但不能搜索np.where
但是使用for
循環和if-else
for index,var in enumerate(groups):
if var == ('Species2', 'Species3'):
print("('Species2', 'Species3') -->>", index)
else:
print("('Species1',) -->>", index)
產量
('Species1',) -->> 0
('Species2', 'Species3') -->> 1
這里的問題可能是array.__contains__()
方式。 看到這里 。 基本上問題是
print(('Species2', 'Species3') in groups)
打印錯誤。 如果你想使用numpy.where
函數,而不是另一個答案所暗示的for循環,最好以某種方式構造一個合適的真值掩碼。 例如
x = np.array(list(map(lambda x: x== ('Species2', 'Species3'), groups)))
print(np.where(x))
給出正確的結果。 可能會有更優雅的方式。
這並不意味着在您使用時從組中搜索元組('Species2','Species3')
np.where(groups == ('Species2', 'Species3'))
它意味着如果您有像這樣的完整數組,請分別搜索'Species2'和'Species3'
groups=np.array([('Species1',''), ('Species2', 'Species3')], dtype=object)
你的數組有兩個元組:
In [53]: groups=np.array([('Species1',), ('Species2', 'Species3')], dtype=object)
In [54]: groups
Out[54]: array([('Species1',), ('Species2', 'Species3')], dtype=object)
In [55]: groups.shape
Out[55]: (2,)
但要小心這種定義。 如果元組的大小都相同,則數組將具有不同的形狀,並且元素將不再是元組。
In [56]: np.array([('Species1',), ('Species2',), ('Species3',)], dtype=object)
Out[56]:
array([['Species1'],
['Species2'],
['Species3']], dtype=object)
In [57]: _.shape
Out[57]: (3, 1)
任何使用where
只能與給它的布爾數組一樣好。 這where
因為平等的測試生產的所有返回空False
:
In [58]: np.where(groups == groups[1])
Out[58]: (array([], dtype=int64),)
In [59]: groups == groups[1]
Out[59]: array([False, False])
如果我使用列表推導來比較組元素:
In [60]: [g == groups[1] for g in groups]
Out[60]: [False, True]
In [61]: np.where([g == groups[1] for g in groups])
Out[61]: (array([1]),)
但是對於這種事情,列表也同樣好
In [66]: alist = [('Species1',), ('Species2', 'Species3')]
In [67]: alist.index(alist[1])
Out[67]: 1
In [68]: alist.index(('Species1',))
Out[68]: 0
In [69]: alist.index(('Species2',))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-69-0b16b56ad28c> in <module>
----> 1 alist.index(('Species2',))
ValueError: ('Species2',) is not in list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.