Python中numpy的where()函數

來源:互聯網
上載者:User

標籤:random   numpy   one   isp   處理   2.4   class   false   log   

第一種用法

np.where(conditions,x,y)

if (condituons成立):

  數組變x

else:

  數組變y

import numpy as np‘‘‘x = np.random.randn(4,4)print(np.where(x>0,2,-2))#試試效果xarr = np.array([1.1,1.2,1.3,1.4,1.5])yarr = np.array([2.1,2.2,2.3,2.4,2.5])zarr = np.array([True,False,True,True,False])result = [(x if c else y)          for x,y,c in zip(xarr,yarr,zarr)]print(result)#where()函數處理就相當於上面那種方案result = np.where(zarr,xarr,yarr)print(result)‘‘‘#發現個有趣的東西# #處理2組數組# #True and True = 0# #True and False = 1# #False and True = 2# #False and False = 3cond2 = np.array([True,False,True,False])cond1 = np.array([True,True,False,False])#第一種處理 太長太醜result = []for i in range(4):    if (cond1[i] & cond2[i]):   result.append(0);    elif (cond1[i]):    result.append(1);    elif (cond2[i]):    result.append(2);    else :  result.append(3);print(result)#第二種 直接where() 很快很方便result = np.where(cond1 & cond2,0,np.where(cond1,1,np.where(cond2,2,3)))print(result)#第三種 更簡便(好像這跟where()函數半毛錢的關係都沒有result = 1*(cond1 & -cond2)+2*(cond2 & -cond1)+3*(-(cond1 | cond2))  (沒想到還可以這麼表達吧)print(result)  
View Code

 

第二種用法

where(conditions) 

相當於給出數組的下標

x = np.arange(16)print(x[np.where(x>5)])#輸出:(array([ 6,  7,  8,  9, 10, 11, 12, 13, 14, 15], dtype=int64),)x = np.arange(16).reshape(-1,4)print(np.where(x>5))#(array([1, 1, 2, 2, 2, 2, 3, 3, 3, 3], dtype=int64), array([2, 3, 0, 1, 2, 3, 0, 1, 2, 3], dtype=int64))#注意這裡是座標是前面的一維的座標,後面是二維的座標
View Code

 

ix = np.array([[False, False, False],       [ True,  True, False],       [False,  True, False]], dtype=bool)print(np.where(ix))#輸出:(array([1, 1, 2], dtype=int64), array([0, 1, 1], dtype=int64))
View Code

 

 

  

Python中numpy的where()函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.