np.newaxis,增加维度

本文通过实例展示了如何使用NumPy的np.newaxis来为一维数组增加维度,包括将一维数组转换为行向量和列向量,并介绍了转换前后数组形状的变化。

np.newaxis,增加维度

In [1]: np.linspace(1, 10, 10)
Out[1]: array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

In [2]: np.linspace(1, 10, 10)[np.newaxis,:]
Out[2]: array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]])

In [3]: np.linspace(1, 10, 10)[:,np.newaxis]
Out[3]:
array([[ 1.],
[ 2.],
[ 3.],
[ 4.],
[ 5.],
[ 6.],
[ 7.],
[ 8.],
[ 9.],
[ 10.]])

In [4]: np.linspace(1, 10, 10).shape
Out[4]: (10,)

In [5]: np.linspace(1, 10, 10)[np.newaxis,:].shape
Out[5]: (1, 10)

In [6]: np.linspace(1, 10, 10)[:,np.newaxis].shape
Out[6]: (10, 1)

np.newaxisNumPy 中用于增加数组维度的关键字,其作用是为数组插入一个新的维度,从而改变数组的形状(shape),增加维度大小为 1。np.newaxis等价于None,可以作为索引使用,用于在指定位置增加一个维度[^1]。 ### 基本使用方法 #### 在第 0 维增加一个维度 ```python import numpy as np arr = np.array([1, 2, 3]) # 原始数组 shape: (3,) new_arr = arr[np.newaxis, :] # shape: (1, 3) print(new_arr) # Output: # [[1 2 3]] ``` #### 在最后一维增加一个维度 ```python import numpy as np arr = np.array([1, 2, 3]) new_arr = arr[..., np.newaxis] print(new_arr.shape) # Output: (3, 1) ``` #### 在指定位置增加一个维度 ```python import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) new_arr = arr[:, np.newaxis, :] print(new_arr.shape) # Output: (2, 1, 3) ``` ### 替换用法 np.newaxis可以替换成None,二者具有一样的效果,只是np.newaxis可读性更强。对于连续的多个":",有更简便的表达方式"..."。例如: ```python import numpy as np a = np.array([1, 2, 3]) b = a[..., None, :] # 等同于 b = a[..., np.newaxis, :] print(b.shape) # Output: (1, 3) ``` ### 更多维度增加示例 - 一维数组变二维数组,在第 0 维增加维度 ```python import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = x[np.newaxis, :] print(y.shape) # Output: (1, 10) ``` - 一维数组变二维数组,在最后一维增加维度 ```python import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = x[:, np.newaxis] print(y.shape) # Output: (10, 1) ``` - 一维数组变三维数组 ```python import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = x[np.newaxis, :, np.newaxis] print(y.shape) # Output: (1, 10, 1) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值