python - 确保 numpy 数组中至少有一定的维度

标签 python numpy

我的工具包中有以下功能并且非常依赖它。我发现很难相信不会有一个 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_3dnp.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/

相关文章:

Python数学游戏算法

python - 当我尝试在一个图上同时使用一个(线)图和一个条形图制作一个图时,我得到一个奇怪的图

python - 条件数据框分组

python "Function call with parameter: Converting measurements?"

python - 使用 TensorFlow 的训练和预测出了什么问题?

python - 为什么我的 Keras 模型在加载后会进行训练,即使我实际上没有提供任何新的训练数据?

python - 如何确定黑盒是多项式还是指数

python - 从数据中查找峰值

python - 对 numpy 数组进行子采样?

python - 将每行的第一个单词分配给字典中的关键字