【问题标题】:Numpy stack in the first dimension?第一维中的numpy堆栈?
【发布时间】:2023-04-05 02:39:02
【问题描述】:

我有两个形状为 (3,8) 的 np.array,我怎样才能把它变成 (2,3,8) 我尝试使用 np.concatenate 但它只给了我

Traceback(最近一次调用最后一次):文件“”,第 1 行,in 文件“array_function internals>”,第 6 行,在 连接类型错误:只能将整数标量数组转换为 标量索引

错误。 我的 a1 数组:

array([[0.08, 0.3, 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3 , 0. , 0.07, 0.17, 0.11, 0.04, 0.05, 0.34]], dtype=float32)

我的 a2 数组:

array([[0.08, 0.3, 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3 , 0. , 0.07, 0.17, 0.11, 0.04, 0.05, 0.34]], dtype=float32)

【问题讨论】:

标签: python arrays numpy


【解决方案1】:

尝试做:

a1 = a1.reshape((1,3,8))
a2 = a2.reshape((1,3,8))
np.concatenate((a1,a2))

array = np.concatenate((a1.reshape((1,3,8)),a2.reshape((1,3,8))))

根据错误消息,您还可能忘记在 np.concatenate() 中的数组周围包含括号。

【讨论】:

    【解决方案2】:

    尝试以下简单的方法来堆叠你的数组:

    >>> import numpy as np
    >>> a = np.array([[0.08, 0.3 , 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3 , 0. , 0.07, 0.17, 0.11, 0.04, 0.05, 0.34]])
    >>> a.shape
    (3, 8)
    >>> b = np.array([[0.08, 0.3 , 0.51, 0.37, 0.02, 0.52, 0.05, 0.08], [0.77, 0.01, 0.08, 0.67, 0.01, 0.02, 0.17, 0.77], [0.3 , 0. , 0.07, 0.17, 0.11, 0.04, 0.05, 0.34]])
    >>> b.shape
    (3, 8)
    >>> c = np.array([a, b])
    >>> c.shape
    (2, 3, 8)
    >>> 
    

    【讨论】:

      【解决方案3】:

      虽然np.concatenate 需要在@Tim Crammond's answer 中创建的现有维度,但np.stack 将为您创建轴:

      np.stack((a, b), axis=0)
      

      这大致相当于@Sophie Roseinsta's suggestion直接使用np.array

      【讨论】:

        猜你喜欢
        • 2019-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-28
        • 1970-01-01
        • 2014-05-01
        • 2017-12-10
        相关资源
        最近更新 更多