python如何對陣列內的元素進行條件運算?

jiangjiane發表於2017-08-28
python裡面陣列運算numpy是首選, C的運算效率, 下面是個簡單例子
>>import numpy as np
>>arr = np.random.rand(5,5) # 5x5的隨機陣列
>>arr
array([[ 0.36401504,  0.87729325,  0.53453396,  0.5031851 ,  0.90744627],
       [ 0.44607108,  0.22673265,  0.77539262,  0.84064101,  0.41774629],
       [ 0.91686641,  0.71480639,  0.09617148,  0.41535823,  0.4175782 ],
       [ 0.25753864,  0.73196495,  0.43557823,  0.97497112,  0.54451645],
       [ 0.58167148,  0.50382906,  0.88490307,  0.77238085,  0.17427672]])
>>mask = arr>0.5 # 選取陣列中元素大於0.5的元素的bool陣列
>>mask
array([[False,  True,  True,  True,  True],
       [False, False,  True,  True, False],
       [ True,  True, False, False, False],
       [False,  True, False,  True,  True],
       [ True,  True,  True,  True, False]], dtype=bool)
>>arr[mask] = 0 # 將陣列中大於0.5的值設為0
>>arr
array([[ 0.36401504,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.44607108,  0.22673265,  0.        ,  0.        ,  0.41774629],
       [ 0.        ,  0.        ,  0.09617148,  0.41535823,  0.4175782 ],
       [ 0.25753864,  0.        ,  0.43557823,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.17427672]])

相關文章