np.newaxis的作用就是在这一位置增加一个一维,这一位置指的是np.newaxis所在的位置,比较抽象,需要配合例子理解。
x1 = np.array([1, 2, 3, 4, 5])
# the shape of x1 is (5,)
x1_new = x1[:, np.newaxis]
# now, the shape of x1_new is (5, 1)
# array([[1],
# [2],
# [3],
# [4],
# [5]])
x1_new = x1[np.newaxis,:]
# now, the shape of x1_new is (1, 5)
# array([[1, 2, 3, 4, 5]])
再来一个例子
In [124]: arr = np.arange(5*5).reshape(5,5)
In [125]: arr.shape
Out[125]: (5, 5)
# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]
In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)
本文详细介绍了numpy.newaxis在数组操作中的作用,通过实例解析如何利用np.newaxis在数组的特定位置增加维度,从而实现从一维到二维、三维等的转换。例如,将一个一维数组转化为二维数组,或者将二维数组升级为五维数组。np.newaxis的使用有助于理解numpy数组的形状变换和广播机制。

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



