本文記錄日常工作中遇到的查找操作,持續更新。
注意:輸入必須是 數組,不能是 list
極值
min,max 返回極值
argmin(a, axis=None, out=None), 返回極值所在的位置;不帶 axis,先拉直,再找極值;帶 axis,找某個維度的極值
b = np.array([[1, 2, 3, 5], [4, 6, 2, 6]]) print(np.max(b)) # 返回最大值 6 print(np.min(b)) # 返回最小值 1 print(np.argmax(b)) # 返回第一個最大值的位置 5 print(np.argmin(b)) # 返回第一個最小值的位置 0 print(np.argmin(b, axis=1)) # [0 2]
NaN值
nan 值由多種表達形式,如 None,np.nan,np.NaN等
isnan,輸入可以是 一維,也可以是 二維,返回布爾索引
x = np.array(range(10), dtype=np.float) y = np.array(range(10,20)) print(x.shape) # (10,) print(x) # [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.] print(y) # [10 11 12 13 14 15 16 17 18 19] x[3] = None # 插入 nan x[5] = np.NaN # 插入 nan print(x) # [ 0. 1. 2. nan 4. nan 6. 7. 8. 9.] # isnan 返回索引 print(np.isnan(x)) # [False False False True False True False False False False] print(y[np.isnan(x)]) # [13 15] print(y[~np.isnan(x)]) # [10 11 12 14 16 17 18 19]
如果想返回數值索引,可如下操作
data4 = np.array([1, 3, np.nan, 5]) ## isnan 返回 nan 值的布爾下標 print np.isnan(data4) # [False False True False] ## where 找到 nan 值的數值下標 print np.where(np.isnan(data4)) # (array([2]),) print np.where(~np.isnan(data4)) # (array([0, 1, 3]),)
注意,nan 值 不能用 where 查找
print(np.where(x != np.NaN)) # (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),) 這樣不行
經常遇到這么一個錯誤
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
錯誤原因:有異常的數據類型,非 int float
解決方法:轉換數據類型,.astype('float')
where 條件
where,返回tuple,第一個值是索引,第二個是空值
1. 輸入必須是 數組,不能是 list
2. 輸入一般是一維,行向量或者列向量都可以
3. 輸入多維,將返回兩個索引,行向量或者列向量返回不同
argwhere,直接返回索引,返回為二維數組,列向量
# list 返回錯誤 data = range(10) print np.where(data>6) # (array([0]),) # 一維數組 data1 = np.array(range(0, 20, 2)) print np.where(data1>6) # (array([7, 8, 9]),) print np.where(data1.T>6) # (array([7, 8, 9]),) # 二維數組 data2 = np.array([range(0, 20, 2)]) print np.where(data2>6) # (array([0, 0, 0]), array([7, 8, 9])) # 多行多列 data3 = np.array([range(10), range(10)]) print(data3) print np.where(data3>6) # (array([0, 0, 0, 1, 1, 1]), array([7, 8, 9, 7, 8, 9])) print np.where(data3.T>6) # (array([7, 7, 8, 8, 9, 9]), array([0, 1, 0, 1, 0, 1])) ## argwhere 直接返回索引 print np.argwhere(data1>6) # [[4] # [5] # [6] # [7] # [8] # [9]] print np.argwhere(data1.T>6) # [[4] # [5] # [6] # [7] # [8] # [9]]
where 也可輸入多個條件
# 求公共部分 print np.intersect1d([1, 4, 3], [3, 4, 5]) # [3 4] # 多個條件 data2 = np.array([1,5, 11,16,20]) print np.where(data2>10) # (array([2, 3, 4]),) print np.where((data2>10) & (data2<18)) # (array([2, 3]),) print np.where(np.logical_and(data2>10, data2<18)) # (array([2, 3]),) print np.intersect1d(np.where(data2>10)[0], np.where(data2<18)[0]) # [2 3]
extract 條件
extract(condition, arr),按某條件查找,返回元素
print(np.extract(np.isnan(x), x)) # [nan nan] print(np.extract(np.isnan(x), y)) # [13 15] print(np.extract(x>8, x)) # [9.]
非0元素
nonzero,返回tuple,第一個值是索引,第二個是空值
x = [1, 0, 3, 0] print(np.nonzero(x)) # (array([0, 2]),)
未完待續...