我的工具包中有以下功能并且非常依赖它。我发现很难相信不会有一个 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
最佳答案
MATLAB 使用默认的 Fortran 顺序,自动在右侧添加维度。 numpy
是默认的 C 顺序,并且更喜欢将它们附加在左侧。
np.array
采用 ndmin
参数,根据需要在前面加上 1。
例如
In [89]: np.array([1,2,3],ndmin=4).shape
Out[89]: (1, 1, 1, 3)
有 3 个 np.atleast_?d
函数。
In [92]: np.atleast_2d([1,2,3]).shape
Out[92]: (1, 3)
In [93]: np.atleast_3d([1,2,3]).shape
Out[93]: (1, 3, 1)
atleast_3d
在 np.dstack
中使用,并且可能是专门为该用途编写的。
广播时,numpy
会根据需要添加维度;发布待定它们需要您的明确操作。这只是开发人员选择的默认 numpy
。
np.ones((3,4,5))+np.zeros((5))
np.array
也接受一个copy
参数
In [113]: x=np.array([1,2,3])
In [114]: y=np.array(x, ndmin=3,copy=False)
In [117]: y.__array_interface__['data']
Out[117]: (152332976, False)
In [118]: x.__array_interface__['data']
Out[118]: (152332976, False)
关于python - 确保 numpy 数组中至少有一定的维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34402228/