功能:np.newaxis是用来给数组a增加维度的
格式:a[np.newaxis和:的组合],如a[:,np.newaxis],a[np.newaxis, np.newaxis, :]
详解:np.newaxis在[]中第几位,a.shape的第几维就变成1,a的原来的维度依次往后排。
例子:若a.shape=(a ,b, c)
a[:, np.newaxis].shape= (a, 1, b, c)
a[:, np.newaxis, np.newaxis].shape= (a, 1, 1, b, c)
a[np.newaxis, :].shape= (1, a, b, c)
a[np.newaxis, np.newaxis, :].shape= (1, 1, a, b, c)
a[np.newaxis, :, np.newaxis].shape= (1, a, 1, b, c)
a[np.newaxis, :, np.newaxis, :].shape= (1, a, 1, b, c)
这么多例子应该看明白了吧。。
实例代码
另外,np.newaxis=None,看代码最后一行
import numpy as np x = np.arange(24).reshape(2, 3, 4) # print('x: ', x) print('x.shape=', x.shape) # print('x[:, np.newaxis]: ', x[:, np.newaxis]) print('x[:, np.newaxis].shape=', x[:, np.newaxis].shape) # print('x[:, np.newaxis, np.newaxis]: ', x[:, np.newaxis, np.newaxis]) print('x[:, np.newaxis, np.newaxis].shape=', x[:, np.newaxis, np.newaxis].shape) # print('x: ', x) print('x.shape=', x.shape) # print('x[np.newaxis, :]: ', x[np.newaxis, :]) print('x[np.newaxis, :].shape=', x[np.newaxis, :].shape) # print('x[np.newaxis, np.newaxis, :]: ', x[np.newaxis, np.newaxis, :]) print('x[np.newaxis, np.newaxis, :].shape=', x[np.newaxis, np.newaxis, :].shape) # print('x[np.newaxis, :, np.newaxis]: ', x[np.newaxis, :, np.newaxis]) print('x[np.newaxis, :, np.newaxis].shape=', x[np.newaxis, :, np.newaxis].shape) # print('x[np.newaxis, :, np.newaxis, :]: ', x[None, :, None, :]) print('x[np.newaxis, :, np.newaxis, :].shape=', x[None, :, None, :].shape) # 另外,np.newaxis=None
x.shape= (2, 3, 4) x[:, np.newaxis].shape= (2, 1, 3, 4) x[:, np.newaxis, np.newaxis].shape= (2, 1, 1, 3, 4) x.shape= (2, 3, 4) x[np.newaxis, :].shape= (1, 2, 3, 4) x[np.newaxis, np.newaxis, :].shape= (1, 1, 2, 3, 4) x[np.newaxis, :, np.newaxis].shape= (1, 2, 1, 3, 4) x[np.newaxis, :, np.newaxis, :].shape= (1, 2, 1, 3, 4)
————————————————
原文链接:https://blog.csdn.net/lllxxq141592654/article/details/85427351