1、简介
Python的lists是非常的灵活以及易于使用。但是在处理科学计算相关大数量的时候,有点显得捉襟见肘了。
Numpy提供一个强大的N维数组对象(ndarray),包含一些列同类型的元素,这点和python中lists不同。
Python lists are extremely flexible and really handy, but when dealing with a large
number of elements or to support scientific computing, they show their limits.
One of the fundamental aspects of NumPy is providing a powerful N-dimensional
array object, ndarray, to represent a collection of items (all of the same type).
2、例子
例子1:创建array数组
In [7]: import numpy as np In [8]: x = np.array([1,2,3]) In [9]: x Out[9]: array([1, 2, 3])
例子2:分片
In [10]: x[1:]
Out[10]: array([2, 3])
和使用python的list一样
例子3:对整个数组进行操作
In [11]: x*2
Out[11]: array([2, 4, 6])
对比python list中同样的操作:
In [1]: alist=[1,2,3] In [2]: alist * 2 Out[2]: [1, 2, 3, 1, 2, 3]
例子4:生成器操作
In [12]: l = [1,2,3] In [13]: [2*li for li in l] Out[13]: [2, 4, 6]
例子5:多个数组之间加法
In [14]: a = np.array([1,2,3]) In [15]: b = np.array([3,2,1]) In [16]: a+b Out[16]: array([4, 4, 4])
例子6:多维数组
In [17]: M = np.array([[1,2,3],[4,5,6]]) In [18]: M[1,2] Out[18]: 6
例子7:arange函数
In [19]: range(6) Out[19]: [0, 1, 2, 3, 4, 5] In [20]: np.arange(6) Out[20]: array([0, 1, 2, 3, 4, 5])