在Python語言中,in是一個使用頻率非常高的運算子,用于判斷物件是否位于字串、元組、串列、集合或字典中,in操作和人的思維方式高度吻合,寫起來近乎于自然語言,充分體現了Python的哲學理念,
>>> 'or' in 'hello world'
True
>>> 5 in {1,2,3,4}
False
>>> 'age' in {'name':'Mike', 'age':18}
True
有趣的是,除了R、javascript、SQL外,包括C/C++在內的主流語言幾乎都不支持in操作,這或許可以解釋為什么Python語言被認為是最容易學習的編程語言,
習慣了使用Python的in運算子,有時就會自然而然地應用到NumPy陣列操作上,比如,下面的寫法看起來沒有任何問題,
>>> import numpy as np
>>> a = np.arange(9)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> 5 in a
True
>>> 10 in a
False
不過,當我嘗試在np.where()函式中使用in運算子的時候,出現了意外,
>>> np.where(a>5)
(array([6, 7, 8], dtype=int64),)
>>> np.where(a%2==0)
(array([0, 2, 4, 6, 8], dtype=int64),)
>>> np.where(a in [2,3,5,7])
Traceback (most recent call last):
File "<pyshell#111>", line 1, in <module>
np.where(a in [2,3,5,7])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
使用a>5或者a%2==0作為條件,np.where()函式沒有問題,但是,使用a in [2,3,5,7],np.where()就會拋出例外,即便寫成下面這樣,也不能得到期望得結果,
>>> np.where(a in np.array([2,3,5,7]))
(array([], dtype=int64),)
難道NumPy不支持兩個陣列之間的in操作嗎?不,強大到宇宙無敵的NumPy,怎么會不支持陣列之間的in操作呢?NumPy不但支持,而且支持得很好,
>>> p = np.array([2,3,5,7]) # 質數陣列
>>> np.in1d(a, p) # 回傳a的每一個元素是否是質數的布爾陣列
array([False, False, True, True, False, True, False, True, False])
>>> np.where(np.in1d(a, p)) # 回傳陣列a中質數的索引序號
(array([2, 3, 5, 7], dtype=int64),)
>>> np.where(np.in1d(a, p), -1, a) # 回傳陣列a中的質數全部替換為-1的結果
array([ 0, 1, -1, -1, 4, -1, 6, -1, 8])
np.in1d()的引數如果是多維陣列,將被自動扁平化,且回傳的布爾陣列也是扁平化的一維陣列,
>>> np.in1d(a.reshape((3,3)), p)
array([False, False, True, True, False, True, False, True, False])
如果np.in1d()的引數是多維的,且期望回傳和原陣列結構相同的布爾陣列,則應使用np.isin()函式,
>>> np.isin(a.reshape((3,3)), p)
array([[False, False, True],
[ True, False, True],
[False, True, False]])
>>> np.where(np.isin(a.reshape((3,3)), p))
(array([0, 1, 1, 2], dtype=int64), array([2, 0, 2, 1], dtype=int64))
若是期望得到兩個陣列的交集而不是交集元素的索引,下面兩種方式都可行,
>>> a[np.where(np.isin(a, p))]
array([2, 3, 5, 7])
>>> np.intersect1d(a, p)
array([2, 3, 5, 7])
第二種方式直接使用np.intersect1d()函式得到兩個陣列的交集,且自動排序,不過,我更喜歡第一種方式,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/278404.html
標籤:AI
