NOTE: 在我一开始学NumPy的时候,并没有真正理解为什么要使用NumPy,只知道很多做ML的都在用这个库,所以就用了。但我觉得在学习NumPy,先理解为什么使用NumPy会对于之后的实践有巨大的帮助。

- 速度快
- Numpy的并行化运算
import time
import numpy as np
size_of_vec = 100000
def pure_python_version():
t1 = time.time()
X = range(size_of_vec)
Y = range(size_of_vec)
Z = [X[i] + Y[i] for i in range(len(X)) ]
return time.time() - t1
def numpy_version():
t1 = time.time()
X = np.arange(size_of_vec)
Y = np.arange(size_of_vec)
Z = X + Y
return time.time() - t1
t1 = pure_python_version()
t2 = numpy_version()
print(t1, t2)
print("Numpy is in this example " + str(t1/t2) + " faster!")0.021614789962768555 0.0003986358642578125
Numpy is in this example 54.22188995215311 faster!-
NumPy数据结构内存占用小
-
更多功能
>>> import numpy as np
>>> np.array([1,2]) + np.array([3,4])
array([4, 6])
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> np.array([1,2]) * np.array([3,4])
array([3, 8])
>>> [1, 2] * [3, 4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'list'
>>> np.array([1,2]) * 2
array([2, 4])
>>> [1, 2] * 2
[1, 2, 1, 2]
