1.NumPy 简介
NumPy 是Python 中科学计算的核心库。NumPy 库中的核心对象是 NumPy 数组。NumPy 数组是一个高性能多维数组对象,专门用于执行数学运算、线性代数和概率计算。使用 NumPy 数组通常比使用 Python 列表快得多,而且需要的代码更少。NumPy 库的很大一部分由 C 代码组成,Python API 充当这些 C 函数的包装器。这是 NumPy 如此之快的原因之一。
大多数流行的机器学习、深度学习和数据科学库都在底层使用 NumPy:
- Scikit-learn
- Matplotlib
- pandas
使用 NumPy 可以轻松实现的不同用例和操作:
- 点积/内积
- 矩阵乘法
- 元素矩阵乘积
- 求解线性系统
- 逆
- 行列式
- 选择随机数(例如高斯/均匀)
- 使用以数组形式表示的图像
2. 安装和阵列基础知识
使用pip或Anaconda安装。
$ pip install numpy
or
$ conda install numpy
导入 numpy
import numpy as np
检查版本
np.__version__
# --> 1.19.1
中心对象是数组
a = np.array([1,2,3,4,5])
a # [1 2 3 4 5]
a.shape # shape of the array: (5,)
a.dtype # type of the elements: int32
a.ndim # number of dimensions: 1
a.size # total number of elements: 5
a.itemsize # the size in bytes of each element: 4
基本方法
a = np.array([1,2,3])
# access and change elements
print(a[0]) # 1
a[0] = 5
print(a) # [5 2 3]
# elementwise math operations
b = a * np.array([2,0,2])
print(b) # [10 0 6]
print(a.sum()) # 10
3. 数组与列表
l = [1,2,3]
a = np.array([1,2,3]) # create an array from a list
print(l) # [1, 2, 3]
print(a) # [1 2 3]
# adding new item
l.append(4)
#a.append(4) error: size of array is fixed
# there are ways to add items, but this essentially creates new arrays
l2 = l + [5]
print(