1. 程式人生 > >numpy基礎教程--where函式的使用

numpy基礎教程--where函式的使用

在numpy中,where函式是一個三元運算子,函式原型為where(condition, x, y),意思是當條件成立的時候,將矩陣的值設定為x,否則設定為y

一個很簡單的應用就是,在一個矩陣當中,將大於或等於平均值的數設定為1,將小於平均值的數設定為0

 

 1 import numpy as np
 2 # 隨機生成一個3行四列的矩陣,範圍是1--16
 3 np.random.seed(10)
 4 t = np.random.randint(1, 16,(3, 4), dtype=int)
 5 print(t)
 6 print("*"*30)
 7 t_mean = t.mean()
8 print("t的平均數為{0}".format(t_mean)) 9 print("*"*30) 10 # 使用where函式可以快速將一個矩陣裡面,小於平均數的值設定為0,大於平均數的值設定為1 11 t1 = np.where(t<t_mean, 0, 1) 12 print(t1)

 

執行結果如下圖所示