通用函数(ufunc),是一种在 ndarray 数据中进行逐元素操作的函数。
一元通用函数
In [1]: import numpy as np
In [2]: arr = np.arange(10)
In [3]: arr
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [4]: np.sqrt(arr)
Out[4]:
array([0. , 1. , 1.41421356, 1.73205081, 2. ,
2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ])
In [5]: np.exp(arr)
Out[5]:
array([1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01,
5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03,
2.98095799e+03, 8.10308393e+03])
In [6]:
二元通用函数
In [6]: x = np.random.randn(8)
In [7]: y = np.randoom.randn(8)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-2458dd362115> in <module>
----> 1 y = np.randoom.randn(8)
AttributeError: module 'numpy' has no attribute 'randoom'
In [8]: y = np.random.randn(8)
In [9]: x
Out[9]:
array([-2.18256212, -0.08144067, -0.08418644, -0.01270041, -0.78696876,
-0.46798034, -0.22818082, -0.69275325])
In [10]: y
Out[10]:
array([ 0.69679623, 1.73440592, 0.96581309, -0.12895321, -1.30429304,
1.23067988, 0.45521522, 0.60378768])
In [11]: np.maximum(x, y)
Out[11]:
array([ 0.69679623, 1.73440592, 0.96581309, -0.01270041, -0.78696876,
1.23067988, 0.45521522, 0.60378768])
numpy.maximum
逐个元素地将 x
和 y 中元素的最大值计算出来。
一些 ufunc 返回多个数组
In [12]: arr = np.random.randn(7) * 5
In [13]: arr
Out[13]:
array([ 4.06149543, -0.66663476, -0.95013597, -2.28401568, -2.44863962,
3.16878977, 3.11914078])
In [14]: remainder, whole_part = np.modf(arr)
In [15]: remainder
Out[15]:
array([ 0.06149543, -0.66663476, -0.95013597, -0.28401568, -0.44863962,
0.16878977, 0.11914078])
In [16]: whole_part
Out[16]: array([ 4., -0., -0., -2., -2., 3., 3.])
modf 返回一个浮点值数组的小数部分和整数部分。
通用函数接受一个可选参数 out 。
In [35]: arr
Out[35]:
array([2.01531522, nan, nan, nan, nan,
1.78010948, 1.76610894])
In [36]: arr2 = np.zeros(7)
In [37]: np.sqrt(arr, arr2)
Out[37]:
array([1.41961798, nan, nan, nan, nan,
1.33420744, 1.32895031])
In [38]: arr2
Out[38]:
array([1.41961798, nan, nan, nan, nan,
1.33420744, 1.32895031])