通用函数
通用函数是一种在ndarray数据中进行逐元素操作的函数。有点象向量化运算,批量进行。
一般有一元通用函数,还有二元通用函数。
import numpy as np
arr = np.array([1,2,3,4,5])
#一元通用函数比如比如开方
np.sqrt(arr)
array([1. , 1.41421356, 1.73205081, 2. , 2.23606798])
>>> np.exp(arr)
array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003,
148.4131591 ])
#二元函数比如比较大小
>>> x = np.random.randn(8)
>>> y = np.random.randn(8)
>>> x
array([ 0.92751113, -0.61084628, -1.03429296, -1.08340597, 1.59195409,
-0.03089959, -0.70825177, 0.71960311])
>>> y
array([-0.83211171, -0.7428019 , 0.57377808, -0.60209485, 1.4694408 ,
0.45792373, 0.30573333, -0.17472197])
>>> np.maximum(x,y)
array([ 0.92751113, -0.61084628, 0.57377808, -0.60209485, 1.59195409,
0.45792373, 0.30573333, 0.71960311])
#np.maximum 逐个将x,y中的元素的最大值计算出来。
>>> x
array([ 0.92751113, -0.61084628, -1.03429296, -1.08340597, 1.59195409,
-0.03089959, -0.70825177, 0.71960311])
>>> np.sign(x)
array([ 1., -1., -1., -1., 1., -1., -1., 1.])
>>> np.ceil(x)
array([ 1., -0., -1., -1., 2., -0., -0., 1.])
>>> np.floor(x)
array([ 0., -1., -2., -2., 1., -1., -1., 0.])
>>> np.rint(x)
array([ 1., -1., -1., -1., 2., -0., -1., 1.])
>>> np.modf(x)
(array([ 0.92751113, -0.61084628, -0.03429296, -0.08340597, 0.59195409,
-0.03089959, -0.70825177, 0.71960311]), array([ 0., -0., -1., -1., 1., -0., -0., 0.]))
>>> np.isnan(x)
array([False, False, False, False, False, False, False, False])
>>> np.cos(x)
array([ 0.59982726, 0.81916292, 0.51113376, 0.46832172, -0.02115619,
0.99952265, 0.75950027, 0.75206737])
>>> np.logical_not(x)
array([False, False, False, False, False, False, False, False])
二元通用函数:
>>> x
array([ 0.92751113, -0.61084628, -1.03429296, -1.08340597, 1.59195409,
-0.03089959, -0.70825177, 0.71960311])
>>> y
array([-0.83211171, -0.7428019 , 0.57377808, -0.60209485, 1.4694408 ,
0.45792373, 0.30573333, -0.17472197])
>>> np.add(x,y)
array([ 0.09539942, -1.35364818, -0.46051488, -1.68550082, 3.0613949 ,
0.42702415, -0.40251844, 0.54488114])
>>> np.subtract(x,y)
array([ 1.75962284, 0.13195563, -1.60807103, -0.48131112, 0.12251329,
-0.48882332, -1.0139851 , 0.89432508])
>>> np.divide(x,y)
array([-1.11464737, 0.82235422, -1.80260105, 1.79939417, 1.08337409,
-0.06747758, -2.3165671 , -4.11856116])
>>> np.maximum(x,y)
array([ 0.92751113, -0.61084628, 0.57377808, -0.60209485, 1.59195409,
0.45792373, 0.30573333, 0.71960311])
总之,通用函数都会将函数的操作针对数组中的每个元素,逐各进行。不用Python一样需要写for循环。