> For the complete documentation index, see [llms.txt](https://johannesliu.gitbook.io/data-science-python-implemented/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johannesliu.gitbook.io/data-science-python-implemented/7.0-numpy_foundation/7.3-basic_manipulation.md).

# 7.3 NumPy基础操作

## 7.3.1 通用函数

## 7.3.2 数组索引

数组可以使用扩展的Python切片语法array\[selection]进行索引。

| 方法          | 描述                         |
| ----------- | -------------------------- |
| x\[i]       | 索引第i个元素                    |
| x\[-i]      | 反向索引第i个元素                  |
| x\[m: n]    | 以默认步长1从第m+1个元素索引至第n-1个元素   |
| x\[-m:-n]   | 以默认步长1从倒数第m个元素索引至倒数第n-1个元素 |
| x\[m, n, j] | 以步长j从从第m+1个元素索引至第n-1个元素    |

数组可以使用类似序列对象类型的语法进行索引:

\[]: x\[1, 2] #查看第2行第3列的元素

\[]:6.0

\[]:x\[:,1]#查看第二列元素

\[]:array(\[2., 5., 8.])

\[]:x\[1] #查看第二行元素

\[]:array(\[4., 5., 6.])

## 7.2.3 数组算术

ndarray对象类型可以对数组元素进行批量操作，这种特性称为矢量化。

\[]:x\*x

\[]:array(\[\[ 2., 4., 6.],

\[ 8., 10., 12.],

\[14., 16., 18.]])

\[]:x-x

\[]:array(\[\[0., 0., 0.],

\[0., 0., 0.],

\[0., 0., 0.]])

\[]:x\*x

\[]:array(\[\[ 1., 4., 9.],

\[16., 25., 36.],

\[49., 64., 81.]])

\[]:x/x

\[]:array(\[\[1., 1., 1.],

\[1., 1., 1.],

\[1., 1., 1.]])

\[]:x\*\*x

\[]:array(\[\[1.00000000e+00, 4.00000000e+00, 2.70000000e+01],

\[2.56000000e+02, 3.12500000e+03, 4.66560000e+04],

\[8.23543000e+05, 1.67772160e+07, 3.87420489e+08]])

## 7.3.4 数组属性

ndarray数组常用属性如下表：

| 属性                                                                                                                              | 描述                                                                 |
| ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| [**ndarray.flags**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flags.html#numpy.ndarray.flags)          | 数组内存布局信息                                                           |
| [**ndarray.shape**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html#numpy.ndarray.shape)          | 数组的形状                                                              |
| [**ndarray.strides**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html#numpy.ndarray.strides)    | Tuple of bytes to step in each dimension when traversing an array. |
| [**ndarray.ndim**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.html#numpy.ndarray.ndim)             | 数组维数                                                               |
| [**ndarray.data**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.data.html#numpy.ndarray.data)             | 包含数组元素的缓存地址                                                        |
| [**ndarray.size**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.size.html#numpy.ndarray.size)             | 数组元素的个数                                                            |
| [**ndarray.itemsize**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.itemsize.html#numpy.ndarray.itemsize) | 每个数组元素的字节大小                                                        |
| [**ndarray.nbytes**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.nbytes.html#numpy.ndarray.nbytes)       | 数组元素的总字节数                                                          |
| [**ndarray.T**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.T.html#numpy.ndarray.T)                      | 数组转置，与transpose()方法相同                                              |
| [**ndarray.real**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.real.html#numpy.ndarray.real)             | 数组的实部                                                              |
| [**ndarray.imag**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.imag.html#numpy.ndarray.imag)             | 数组的虚部                                                              |
| [**ndarray.flat**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html#numpy.ndarray.flat)             | 一维数组迭代器                                                            |

下面我们查看ndarray对象x的相关属性：

\[]:x.flags

\[]: C\_CONTIGUOUS : True

F\_CONTIGUOUS : False

OWNDATA : True

WRITEABLE : True

ALIGNED : True

WRITEBACKIFCOPY : False

UPDATEIFCOPY : False

\[]:x.nbytes

\[]:72

## 7.3.5 数组方法

接下来我们介绍常用数组方法：

### 数组创建

可以使用下列方法来创建数组对象

| 方法                                | 描述                         |
| --------------------------------- | -------------------------- |
| ndarray.array(\[x, …], dtype=int) | 使用Python列表和元组创建ndarray数组   |
| ndarray.arange(m, n, i)           | 创建一个从m到n，以i为步长的ndarray数组   |
| ndarray.linspace(m, n, l)         | 创建一个从m到n，等分为l个元素的ndarray数组 |
| ndarray.indices((m,n ))           | 创建一个m行n列矩阵                 |
| nndarray.random.rand(m, n)        | 创建一个m行n列的随机数组              |
| np.ones((m, n), dtype)            | 创建一个m行n列全1数组               |
| np.empty((m, n), dtype)           | 创建一个m行n列全0数组               |

创建一个3行5列的全1数组：

\[]:np.ones((3,5))

\[]:array(\[\[1., 1., 1., 1., 1.],

\[1., 1., 1., 1., 1.],

\[1., 1., 1., 1., 1.]])

创建一个4行5列的随机数组

\[]:array(\[\[1., 1., 1., 1., 1.],

\[1., 1., 1., 1., 1.],

\[1., 1., 1., 1., 1.]])

\[]:array(\[\[0.02056306, 0.71741279, 0.90432924, 0.73616127, 0.63019217],

\[0.71198986, 0.23522983, 0.76942657, 0.74224889, 0.0969868 ],

\[0.15701329, 0.05086768, 0.83441576, 0.1043487 , 0.33995561],

\[0.25604749, 0.63719473, 0.20883015, 0.75983402, 0.67768955]])

### 数组转换

可以使用下列方法对ndarray对象进行转换

| 方法                                                                                                                                         | 描述                           |
| ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------- |
| [ndarray.item](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.item.html#numpy.ndarray.item)(\*args)                    | 将数组的元素复制到标准Python标量并返回它。     |
| [ndarray.tolist](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html#numpy.ndarray.tolist)()                    | 以(可能是嵌套的)列表的形式返回数组。          |
| [ndarray.itemset](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.itemset.html#numpy.ndarray.itemset)(\*args)           | 将标量插入数组(如果可能，标量将转换为数组的dtype) |
| [ndarray.tofile](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html#numpy.ndarray.tofile)(fid\[, sep, format]) | 将数组以文本或二进制形式写入文件(默认值)。       |
| [ndarray.copy](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.copy.html#numpy.ndarray.copy)(\[order])                  | 返回数组的副本。                     |
| [ndarray.view](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html#numpy.ndarray.view)(\[dtype, type])            | 具有相同数据的数组的新视图。               |
| [ndarray.fill](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.fill.html#numpy.ndarray.fill)(value)                     | 用标量值填充数组。                    |

将一个大小维的三维随机数组转为列表形式

\[]:np.random.rand(2,3,2).tolist()

\[]:\[\[\[0.6522732091435327, 0.30567594621945293],

\[0.6144978942635615, 0.00535896256724222],

\[0.20425276599130826, 0.012501269195163922]],

\[\[0.9406005870981111, 0.6682967703772825],

\[0.23029639908927446, 0.9903955382985428],

\[0.6846793144592922, 0.6686806969051653]]]

形状操纵

对于重新塑造、调整大小和转置，可以用n个整数替换单个元组参数，这些整数将被解释为一个n元组。

| [**ndarray.reshape**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.reshape.html#numpy.ndarray.reshape)(shape\[, order])      | 返回包含具有新形状的相同数据的数组。      |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| [**ndarray.resize**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.resize.html#numpy.ndarray.resize)(new\_shape\[, refcheck]) | 改变数组的形状                 |
| [**ndarray.transpose**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.transpose.html#numpy.ndarray.transpose)(\*axes)         | 返回数组的转置                 |
| [**ndarray.swapaxes**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.swapaxes.html#numpy.ndarray.swapaxes)(axis1, axis2)      | 返回交换了axis1和axis2的数组的视图。 |
| [**ndarray.flatten**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html#numpy.ndarray.flatten)(\[order])             | 返回折叠成一维的数组的副本。          |
| [**ndarray.ravel**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ravel.html#numpy.ndarray.ravel)(\[order])                   | 返回一个扁平数组                |

将一个大小为的2维随机数组展平:

\[]:np.random.rand(2,3,2).flatten()

\[]:array(\[0.55389146, 0.29099669, 0.49944941, 0.75609966, 0.59443963,

0.10997695, 0.52392316, 0.81634779, 0.86769176, 0.35935143,

0.03287644, 0.69989962])

将一个大小为的2维随机数组随机数组重塑为的随机数组:

\[]:x=np.random.rand(2,3)

x

\[]:array(\[\[0.67406133, 0.3566374 , 0.2665187 ],

\[0.24009316, 0.59855278, 0.32029325]])

\[]:x.reshape(3,2)

\[]:array(\[\[0.67406133, 0.3566374 ],

\[0.2665187 , 0.24009316],

\[0.59855278, 0.32029325]])

### 数组计算

可以使用下列方法对ndarray数组进行计算:

| [ndarray.argmax](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.argmax.html#numpy.ndarray.argmax)(\[axis, out])                     | Return indices of the maximum values along the given axis. 返回指定轴上最大值的索引。 |
| ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| [ndarray.min](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.min.html#numpy.ndarray.min)(\[axis, out, keepdims])                    | 返回指定轴上得最小值                                                               |
| [ndarray.argmin](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.argmin.html#numpy.ndarray.argmin)(\[axis, out])                     | 返回指定轴上最小值得索引。                                                            |
| [ndarray.ptp](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ptp.html#numpy.ndarray.ptp)(\[axis, out, keepdims])                    | 返回指定轴轴的数值波动范围                                                            |
| [ndarray.clip](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.clip.html#numpy.ndarray.clip)(\[min, max, out])                       | 以数组形式返回指定范围内的元素。                                                         |
| [ndarray.round](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.round.html#numpy.ndarray.round)(\[decimals, out])                    | 返回四舍五入到特定位数的小数。                                                          |
| [ndarray.trace](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.trace.html#numpy.ndarray.trace)(\[offset, axis1, axis2, dtype, out]) | 返回数组对角线的和。                                                               |
| [ndarray.sum](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.sum.html#numpy.ndarray.sum)(\[axis, dtype, out, keepdims])             | 返回给定轴上数组元素的和。                                                            |
| [ndarray.mean](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.mean.html#numpy.ndarray.mean)(\[axis, dtype, out, keepdims])          | 返回数组元素沿给定轴的平均值。                                                          |
| [ndarray.var](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.var.html#numpy.ndarray.var)(\[axis, dtype, out, ddof, keepdims])       | 返回数组元素沿给定轴的方差。                                                           |
| [ndarray.std](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.std.html#numpy.ndarray.std)(\[axis, dtype, out, ddof, keepdims])       | 返回数组元素沿给定轴的标准差。                                                          |
| [ndarray.prod](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.prod.html#numpy.ndarray.prod)(\[axis, dtype, out, keepdims])          | 返回数组元素在给定轴上的乘积                                                           |

上述方法对axis轴进行计算。的axis参数如果维None，则将数组视作一维数组。

例：创建一个大小为3×3×3的三维数组，对它的三个轴求和

\[]:x=np.random.rand(3,3,3)

x

\[]:array(\[\[\[0.57982037, 0.41002888, 0.72101916],

\[0.93451008, 0.47677948, 0.55761938],

\[0.3703933 , 0.54361156, 0.95946646]],

\[\[0.73779921, 0.08440105, 0.00188711],

\[0.32432818, 0.2609275 , 0.61720936],

\[0.77805538, 0.69264117, 0.75065842]],

\[\[0.56759239, 0.16964658, 0.5724592 ],

\[0.42525304, 0.89439075, 0.76269357],

\[0.649416 , 0.30066668, 0.46065574]]])

\[]:x.sum(axis=0), x.sum(axis=1), x.sum(axis=2)

\[]:(array(\[\[1.88521197, 0.66407651, 1.29536547],

\[1.6840913 , 1.63209773, 1.93752231],

\[1.79786468, 1.5369194 , 2.17078062]]),

array(\[\[1.88472375, 1.43041992, 2.23810499],

\[1.84018276, 1.03796971, 1.36975488],

\[1.64226143, 1.36470401, 1.79580851]]),

array(\[\[1.71086841, 1.96890893, 1.87347132],

\[0.82408737, 1.20246503, 2.22135496],

\[1.30969818, 2.08233737, 1.41073841]]))

一些方法带有out参数，可以将结果输出到out参数指定的数ndarray组中。
