如何返回至少4D的数组:模拟numpy.atleast_4d的有效方法 [英] How to return an array of at least 4D: efficient method to simulate numpy.atleast_4d
问题描述
numpy提供了三个方便的例程,可将一个数组转换为至少一个1D,2D或3D数组,例如通过 numpy.atleast_3d
numpy provides three handy routines to turn an array into at least a 1D, 2D, or 3D array, e.g. through numpy.atleast_3d
我还需要一个等效的维度:atleast_4d
.我可以想到使用多种嵌套if语句的各种方式,但是我想知道是否有一种更有效,更快的方法来返回所讨论的数组.在您的回答中,如果可以的话,我很想看到执行速度的估计值(O(n)).
I need the equivalent for one more dimension: atleast_4d
. I can think of various ways using nested if statements but I was wondering whether there is a more efficient and faster method of returning the array in question. In you answer, I would be interested to see an estimate (O(n)) of the speed of execution if you can.
推荐答案
The np.array
method has an optional ndmin
keyword argument that:
指定结果数组的最小维数 应该有.可以根据需要预先固定形状 这个要求.
Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
如果还设置了copy=False
,则应该接近所追求的目标.
If you also set copy=False
you should get close to what you are after.
作为自己动手的替代方法,如果您想要尾随而不是前导附加尺寸:
As a do-it-yourself alternative, if you want extra dimensions trailing rather than leading:
arr.shape += (1,) * (4 - arr.ndim)
这篇关于如何返回至少4D的数组:模拟numpy.atleast_4d的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!