Scott's Blog

学则不固, 知则不惑

0%

Numpy Universal Functions

Numpy中一些基本函数参考。

Universal Functions

Universal Functions 也叫 ufunc,比如开根 sqrtexp:

Sqrt:

1
2
3
4
5
6
arr = np.arange(10)
np.sqrt(arr)
输出:

array([ 0. , 1. , 1.41421356, 1.73205081, 2. ,
2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ])

exp:

1
2
3
4
5
6
7
np.exp(arr)
输出:

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])

你有两个数组,它们的长度都是一样的,你需要对比两个数组中对应的值,返回大的:

1
2
3
4
5
6
7
8
9
10
11
12
13
a = np.random.randn(1,10)*10
# 输出

array([[ 7.45106569, 2.47039999, 13.3143474 , 11.73359137,
-5.16471496, 3.37688733, -3.03783497, 13.94821303,
-13.79166595, 4.35553629]])

b = np.random.randn(1,10)*10
# 输出

array([[ 0.73315303, 5.87494888, 4.01168595, 3.78652398,
-0.35151181, -5.61564742, 3.0190971 , -2.28944227,
6.45900038, 14.22907421]])

利用 npmaximun 函数就可以做到:

1
2
3
4
5
6
np.maximum(a,b)
# 输出:

array([[ 7.45106569, 5.87494888, 13.3143474 , 11.73359137,
-0.35151181, 3.37688733, 3.0190971 , 13.94821303,
6.45900038, 14.22907421]])

附录

ufuncs