Python vs Matlab-findとnp.where


matlabのfind関数
matlabのfindの関数の強みは、下付き文字を返すことができ、戻りパラメータの個数に応じて、列で全ソートされた1次元下付き文字(戻りパラメータの個数は1)を返し、行列インデックスの2次元座標(戻りパラメータの個数は2):
>>A = [1, 2, 3; 1, 2, 3; 1, 2, 3]
>>idx = find(A > 2)
idx = 
    7
    8
    9

>>A(idx)
ans
    3
    3
    3
%                  (predicate,  )   
>>A(A>2)
ans
    3
    3
    3

>>[rows, cols] = find(A > 2)
rows = 
        1
        2
        3
cols = 
        3
        3
        3

pythonの一般的な処理
>>a = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>idx = [idx for (idx, val) in enumerate(a) if val > 2]
>>idx
[2, 5, 8]
>>vals = [val for (idx, vals) in enumerate(a) if val > 2]
[3, 3, 3]

pythonにおけるmatlabのfind関数と等価な組み込み関数pythonまたはnumpyのいずれかの条件を満たす下付き文字を返すことができる関数はnp.where()であるが、np.where()listのタイプのパラメータを受け入れず、np.where()は3つのパラメータを受信し、3つの演算に使用してもよいし、1つのパラメータを受信してもよいし、条件を満たす下付き文字を返すことができる.
>>a = np.array(a)
>>a
array([1, 2, 3, 1, 2, 3, 1, 2, 3])
>>idx = np.where(a > 2)
>>idx
(array([2, 5, 8], dtype=int32),)
>>a[idx]               #         
array([3, 3, 3])        
>>a[a>2]               #      
array([3, 3, 3])    
np.where()が三目演算に使用される場合:
>>y = np.array([1, 2, 3, 4, 5, 6])  #         ,       
>>y = np.where(y%2 == 0, y+1, y-1)
>>y 
array([0, 3, 2, 5, 4, 7])

処理NaN(not a number)
nanが存在する列の非nanの平均値をこれらのnan値に割り当てる
>>A = np.array([[1, 2, 3, 4], [5, 6, np.nan, 8], [9, 10, 11, np.nan]])
>>idx = np.where(np.isnan(A))
>>idx
(array([1, 2], dtype=int32), array([2, 3], dtype=int32))
for i in idx:
    A[i[0], i[1]] = A[~np.isnan(A[:, i[1]]), i[1]].mean()