You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 2.1.2:形状操作
## 改变形状
上一节介绍了怎样实例化 ndarray 对象,比如想实例化一个 3 行 4 列的二维数组,并且数组中的值全为 0 。就可能会写如下代码:
```python
import numpy as np
a = np.zeros((3, 4))
```
那如果想把 a 变成 4 行 3 列的二维数组,怎么办呢?机智的您可能会想到这样的代码:
```python
import numpy as np
a = np.zeros((3, 4))
# 直接修改shape属性
a.shape = [4, 3]
```
最后您会发现,这样的代码可以完成功能,但是这种直接改属性的方式太粗暴了,不符合良好的编程规范。
更加**优雅的解决方式**是使用 NumPy 为我们提供了一个用来改变 ndarray 对象的 shape 的函数,叫**reshape**。
NumPy 为了照顾偏向于面向对象或者这偏向于面向过程这两种不同风格的程序员,提供了两种调用**reshape**函数的方式(**其实很多函数都提供了两种风格的接口**)。
如果你更偏向于面向对象,那么你可以想象成 ndarray 对象中提供好了一个叫 reshape 成员函数。代码如下:
```python
import numpy as np
a = np.zeros((3, 4))
# 调用a的成员函数reshape将3行4列改成4行3列
a = a.reshape((4, 3))
```
如果你更偏向于面向过程NumPy 在它的作用域内实现了 reshape 函数。代码如下:
```python
import numpy as np
a = np.zeros((3, 4))
# 调用reshape函数将a变形成4行3列
a = np.reshape(a, (4, 3))
```
**不过需要注意的是,不管是哪种方式的 reshape ,都不会改变源 ndarray 的形状,而是将源 ndarray 进行深拷贝并进行变形操作,最后再将变形后的数组返回出去。也就是说如果代码是`np.reshape(a, (4, 3))`那么 a 的形状不会被修改!**
如果想优雅的直接改变源 ndarray 的形状,可以使用 resize 函数。代码如下:
```python
import numpy as np
a = np.zeros((3, 4))
# 将a从3行4列的二维数组变成一个有12个元素的一维数组
a.resize(12)
print(a)
```
输出如下:
```python
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
```
有的时候懒得去算每个维度上的长度是多少,比如现在有一个 6 行 8 列的 ndarray ,然后想把它变形成有 2 列的 ndarray (**行的数量我懒得去想**),此时我们可以在行的维度上传个 -1 即可,代码如下:
```python
import numpy as np
a = np.zeros((6, 8))
# 行的维度上填-1会让numpy自己去推算出行的数量很明显行的数量应该是24
a = a.reshape((-1, 2))
```
也就是说在变形操作时,如果某个维度上的值为 -1 ,那么该维度上的值会根据其他维度上的值自动推算。
**-1 虽好,可不能贪杯!如果代码改成 `a = a.reshape((-1, -1))` NumPy 会认为你是在刁难他,并向你抛出异常 `ValueError: can only specify one unknown dimension`。**