首页 > 其他分享 >Numpy | np.newaxis()函数

Numpy | np.newaxis()函数

时间:2022-11-25 11:45:00浏览次数:39  
标签:维度 shape print add newaxis np Numpy

np.newaxis

np.newaxis 的功能是增加新的维度,但是要注意 np.newaxis 放的位置不同,产生的矩阵形状也不同。

通常按照如下规则:

np.newaxis 放在哪个位置,就会给哪个位置增加维度

x[:, np.newaxis] ,放在后面,会给列上增加维度
x[np.newaxis, :] ,放在前面,会给行上增加维度

用途: 通常用它将一维的数据转换成一个矩阵,这样就可以与其他矩阵进行相乘。

例1:这里的 x 是一维数据,其 shape是 4,可以看到通过在列方向上增加新维度,变成了 4 x 1 的矩阵,也就是在 shape 的后面发生了变化。

x = np.array([1, 2, 3, 4])
print(x.shape)

x_add = x[:, np.newaxis]
print(x_add.shape)
print(x_add)
>>>
(4,)
(4, 1)
[[1]
 [2]
 [3]
 [4]]

例2:通过在行方向上增加新的维度,变成了 1 x 4 的矩阵,也就是在 shape 的前面发生了变化。

x = np.array([1, 2, 3, 4])
print(x.shape)

x_add = x[np.newaxis, :]
print(x_add.shape)
print(x_add)
>>>
(4,)
(1, 4)
[[1 2 3 4]]

例3:给矩阵增加一个维度。

x = np.array([[1, 2, 3, 4], [2, 3, 4, 5]])
print(x.shape)

x_add = x[:, np.newaxis]
print(x_add)
print(x_add.shape)

>>>
(2, 4)
[[[1 2 3 4]]
 [[2 3 4 5]]]
(2, 1, 4)

例四:取第三列并增加一个维度。

x = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [6, 7, 8, 9]])
print(x.shape)

x_add = x[:, np.newaxis,2]
print(x_add)
print(x_add.shape)

标签:维度,shape,print,add,newaxis,np,Numpy
From: https://www.cnblogs.com/zhang-lunqi/p/16924620.html

相关文章