我在我的工具箱中具有以下功能并且严重依赖它。我觉得很难相信这样做不会有一个颠簸的内建,但是我在numpy中搜索可能的函数名称,以及谷歌搜索这个问题的各种解释,并没有发现任何东西。有什么吗?确保numpy数组中至少具有某种维度
def project(a, maxdim):
"""
Return a view of the numpy array <a> that has at least <maxdim>+1
dimensions (pad a.shape with 1's on the right if necessary).
"""
if isinstance(a, numpy.matrix) and maxdim > 1: a = numpy.asarray(a)
else: a = a.view()
a.shape += (1,) * (maxdim-len(a.shape)+1)
return a
我没有看到你的if语句点;对numpy.asarray的调用将完成同样的事情。这留下了一个相当简单的单线,不,我不认为它比这更简单。 –
@EelcoHoogendoorn两行:一个创建副本,一个扩展状态。任何超过1行的值都是值得的。 – jez
np.asarray(a).reshape(*(shape +(1,)*(maxdim + 1-a.ndim))) 可以说,尽管如此,仍然值得做一个函数。 –