![](/img/trans.png)
[英]Faster numpy array indexing when using condition (numpy.where)?
[英]Apply numpy.where on condition with either list or numpy.array
我發現numpy.where
在應用於foo==2
等條件時表現不同,當foo
是列表或foo
是numpy.array
foo = ["a","b","c"]
bar = numpy.array(["a","b","c"])
numpy.where(foo == "a") # Returns array([])
numpy.where(bar == "a") # Returns array([0])
我希望使用相同的命令使其適用於list或numpy.array,我擔心如何有效地執行此操作。 以下是否可以?
numpy.where(numpy.array(foo, copy=False) == "a") # Returns array([0])
numpy.where(numpy.array(bar, copy=False) == "a") # Returns array([0])
結果如預期,但這是滿足我需求的最佳方式嗎? 每次使用numpy.array
構造函數是確保對象類型的最佳方法嗎?
謝謝 !
對我來說,你的解決方案已經是最好的:
numpy.where(numpy.array(foo, copy=False) == "a")
由於copy=False
,它簡潔,非常清晰且完全有效。
如果您真的在尋找最numpy
-esque解決方案,請使用np.asarray
:
numpy.where(numpy.asarray(foo) == "a")
如果您還希望您的代碼使用numpy.ndarray
子類,而不將它們“下轉換”為它們的基類ndarray
,那么使用np.asanyarray
:
numpy.where(numpy.asanyarray(foo) == "a")
例如,這適用於np.matrix
,而不將其轉換為數組。 我想這也可以確保在檢查之前不會將np.matrix
實例復制或重構為數組。
注意:我認為副本是由np.array
為列表創建的,因為它需要構造數組對象。 這可以在np.array
的文檔中np.array
:
copy : bool, optional
If true (default), then the object is copied.
Otherwise, a copy will only be made if __array__ returns a copy, if
obj is a nested sequence, or if a copy is needed to satisfy any of the
other requirements (dtype, order, etc.).
在這種情況下, np.asarray
也會復制一份。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.