NumPy

NumPy 是一个运行速度非常快的 Python 数学库,主要用于数组计算。 这里总结一些常用的功能,供查阅。

开始使用NumPy

对于使用 Python 库,第一步必然是import

import numpy as np

Numpy Array 数组

NumPy 的核心是数组 (arrays)。具体来说是多维数组 (ndarrays)。其中几个常用的属性和方法:

创建数组

访问数组

基本操作

ndarray 和一个数字运算

两个ndarray间的运算

统计函数

数组所有元素的和的一元操作。通过指定 axis 参数可以将操作应用于数组的某一具体 axis 。

全局函数 universal functions

全局函数操作数组中每个元素,输出一个数组。

操作形状

ndarray.reshape(shape)

ndarray.resize(shape)

ndarray.T

拼接数组

拆分数组

拷贝和 视图 (Views)

在操作数组的时候,数据有时拷贝到新的数组,有时候又不拷贝。

函数和方法总结

NumPy进阶

广播 Broadcasting

广播允许全局函数 (universal functions) 输入不相同的形状的数组。

A (4d array): 8 x 1 x 6 x 1 B (3d array): 7 x 1 x 5 Result (4d array): 8 x 7 x 6 x 5

A (2d array): 5 x 4 B (1d array): 1 Result (2d array): 5 x 4

A (2d array): 15 x 3 x 5 B (1d array): 15 x 1 x 5 Result (2d array): 15 x 3 x 5


下面是 _NumPy_ 官方的几个说明图:
<p align="center">
<img src="https://www.numpy.org/devdocs/_images/theory.broadcast_1.gif" /><br/>
<img src="https://www.numpy.org/devdocs/_images/theory.broadcast_2.gif" /><br/>
<img src="https://www.numpy.org/devdocs/_images/theory.broadcast_3.gif" /><br/>
<img src="https://www.numpy.org/devdocs/_images/theory.broadcast_4.gif" />
</p>

## 高级索引
### 用索引数组索引
``` python
>>> a = np.arange(12)**2
>>> i = np.array([1,1,3,8,5]) # an array of indices
>>> a[i]
array([ 1,  1,  9, 64, 25])
>>>
>>> j = np.array([[3,4],
                  [9,7]])
>>> a[j]
array([[ 9, 16],
       [81, 49]])
>>> a = np.arange(12).reshape(3,4)
>>> a
array([[0, 1,  2,  3],
      [ 4, 5,  6,  7],
      [ 8, 9, 10, 11]])
>>> i = np.array([[0,1],  # indices for the first dim of a
...               [1,2]])
>>> j = np.array([[2,1],  # indices for the second dim
...               [3,3]])
>>>
>>> a[i,j]                # i and j must have equal shape
array([[ 2,  5],
      [ 7, 11]])

使用索引数组对数组赋值:

>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a[[1,3,4]] = 0
>>> a
array([0, 0, 2, 0, 0])

用布尔数组索引

我们可以通过一个布尔数组来索引目标数组,以此找出与布尔数组中值为True的对应的目标数组中的数据。 布尔数组的长度必须与目标数组对应的轴的长度一致。

>>> a = np.arange(12).reshape(3,4)
>>> b = a > 4
>>> b
array([[False, False, False, False],
       [False,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)
>>> a[b]
array([ 5,  6,  7,  8,  9, 10, 11])

选择性赋值:

>>> a[b] = 0
>>> a
array([[0, 1, 2, 3],
       [4, 0, 0, 0],
       [0, 0, 0, 0]])

线性代数

NumPy 可以实现大量的矩阵操作,例如:

linalg中的常用函数:

一些技巧

自动塑形

为了改变数组的维度,你可以省略一个可以自动被推算出来的大小的参数。

>>> a = np.arange(30)
>>> a.shape = 2,-1,3  # -1 means "whatever is needed"
>>> a.shape
(2, 5, 3)

直方图 Histgram

NumPyhistogram 函数应用于数组,返回两个vector:数组的柱状图和 bins 的vector

(n, bins) = np.histogram(v, bins=50, density=True)  # NumPy version (no plot)
plt.plot(.5*(bins[1:]+bins[:-1]), n)
plt.show()

Reference

回到目录