NumPy使用教程(三)面向数组编程
来自http://www.tpleina.com/2019/05/3281302163.html
面向数组编程
NumPy数组通过简单的数组表达式完成多种数据操作任务,数组表达式代替循环的方法称之为向量化
numpy.where
numpy.where
函数是三目运算x if condition else y
的数组版
使用示例
条件+数组+数组形式
import numpy as np
arr1 = np.random.randn(6)
arr2 = np.random.randn(6)
cond = np.array([True,True,True,False,False,False])
print(arr1)
print(arr2)
arr3 = np.where(cond, arr1, arr2)
print(arr3)
# 输出
[ 1.27341434 0.98277035 -0.37508696 -0.10692764 0.61461728 -0.49524537]
[-0.17197977 -1.54415347 2.10698458 -0.59802743 -0.39001325 1.29582979]
[ 1.27341434 0.98277035 -0.37508696 -0.59802743 -0.39001325 1.29582979]
条件+标量+数组形式
import numpy as np
arr = np.random.randint(-50,50,(4,5))
print(arr)
t_num = 10
arr1 = np.where(arr>0, t_num, arr)
print(arr1)