单例维度(dim length = 1)
可以作为形状标准与原始数组形状一起使用np.insert
直接更改其形状,如下所示 -
x.shape = np.insert(x.shape,axis,1)
那么,我们可以通过一些np.diff
和np.cumsum
技巧来扩展它以邀请多个新轴,就像这样 -
insert_idx = (np.diff(np.append(0,axis))-1).cumsum()+1
x.shape = np.insert(x.shape,insert_idx,1)
样例运行 -
In [151]: def addNewAxisAt(x, axis):
...: insert_idx = (np.diff(np.append(0,axis))-1).cumsum()+1
...: x.shape = np.insert(x.shape,insert_idx,1)
...:
In [152]: A = np.random.rand(4,5)
In [153]: addNewAxisAt(A, axis=1)
In [154]: A.shape
Out[154]: (4, 1, 5)
In [155]: A = np.random.rand(5,6,8,9,4,2)
In [156]: addNewAxisAt(A, axis=5)
In [157]: A.shape
Out[157]: (5, 6, 8, 9, 4, 1, 2)
In [158]: A = np.random.rand(5,6,8,9,4,2,6,7)
In [159]: addNewAxisAt(A, axis=(1,3,4,6))
In [160]: A.shape
Out[160]: (5, 1, 6, 1, 1, 8, 1, 9, 4, 2, 6, 7)
numpy.reshape
,可以以非变异的方式完成这个操作。 - user2357112np.insert
的新形状信息。 - Divakarnp.expand_dims
,我接受了使用内置版本的答案。 - Wang