之前一直困惑np.newaxis的用法,每次遇到都一脸懵逼,网上特有不少博客对它的解释,不过大多都是举一些例子,乍一看还是不知所云,摸不着规律
博客https://blog.youkuaiyun.com/lanchunhui/article/details/49725065 中提到,np.newaxis与None等价,作用就是为numpy数组增加一个轴来改变数组维度
import numpy as np
type(np.newaxis)
np.newaxis==None
首先,我们知道可以通过array的shape属性得到维度信息
a=np.array([[1,2,3],[4,5,6]])
print(a.shape)
通过a[np.newaxis,:]或者a[:,np.newaxis]可以改变a的维度
a[np.newaxis,:]
a[:,np.newaxis]
根据np.newaxis出现的位置,在a.shape的对应位置insert一个1,得到的就是改变后的shape,例如
a[np.newaxis,:].shape
a[:,np.newaxis].shape
a[:,:,np.newaxis].shape
当然,也可以增加更多的axis,利用这个规律可以方便算出新的shape
a[np.newaxis,:,np.newaxis,:,np.newaxis].shape
而得到的新的数组就相当于原来的数组做了一次reshape
a[np.newaxis,:,np.newaxis,:,np.newaxis]
a.reshape((1, 2, 1, 3, 1))
本文详细解析了numpy中的np.newaxis使用方法及其如何改变数组维度。通过具体示例,展示了np.newaxis如何在数组的特定位置插入新轴,并与reshape方法进行了对比。
284

被折叠的 条评论
为什么被折叠?



