1. newaxis 增加维度
构建数组
import numpy as npa = np.array([1,2,3])aprint (a.shape,'\n',a)>>> aarray([1, 2, 3])>>> print (a.shape,'\n',a)(3,)[1 2 3]
- a 为 array 数组,为一维数据 (3,)
使用 newaxis
```python a = np.array([1,2,3])[:,np.newaxis] print (a.shape,’\n’,a)
print (a.shape,’\n’,a) (3, 1) [[1] [2] [3]] ```
- 可以看到 shape 发生了变化,有了一列出来。
- 变成三行一列,二维数组
a = np.array([1,2,3])[np.newaxis,:]print (a.shape,'\n',a)>>> print (a.shape,'\n',a)(1, 3)[[1 2 3]]
- 变成一列三行。
- 可以知道与 np.newaxis 放置有关!!放在哪里,哪里多出一维数据
示例
from sklearn import datasets, linear_modeldiabetes = datasets.load_diabetes()# 提取第三列,第一列为0X = diabetes.data[:,2]y = diabetes.data[:, np.newaxis, 2]z = diabetes.data[np.newaxis,:, 2]X.shapey.shapez.shape>>> X.shape(442,)>>> y.shape(442, 1)>>> z.shape(1, 442)
- 就是看 np.newaxis 和 : 的相对位置
