【问题标题】:Writing columns into a NumPy array将列写入 NumPy 数组
【发布时间】:2019-12-07 06:23:37
【问题描述】:

我已经用零初始化了一个用于内存管理的 numpy 数组,我正在尝试将数据写入循环中的每一列。

我来自 Matlab 背景,所以我的代码类似于:

myArray = np.zeros((250000, 100))

for i in range(100):
    x = np.random.rand(250000) # random just to show behavior
    myArray[:,i] = x

我收到了Value Error: could not broadcast input array from shape (250000,1) into shape (250000)

我看到myArray[:,i].shape(250000,),但我不确定如何找到(250000,1)。 Matlab 会隐式执行此操作。

【问题讨论】:

  • 反之,你应该分配= x.ravel()。但由于x 在每个循环中都相同,您可以简单地执行myArray[:] = x
  • 重塑数组的常用方法是使用array.reshape()
  • 无法重现错误。
  • 什么是x?那是你问题的根源。例如,如果 x 是一个常量,它就可以正常工作。
  • 欢迎来到 SO!运行您提供的代码应该没有问题,因为我们任何人都不会出错。 xmyArray[:,i] 的形状都是 (250000,)。查看此帖子以了解有关形状的更多信息:stackoverflow.com/questions/22053050/…

标签: python numpy indexing array-broadcasting


【解决方案1】:

您的示例不会产生错误:

In [120]: arr = np.zeros((4,3))                                                                              
In [121]: arr[:,0] = np.random.rand(4)                                                                       
In [122]: arr                                                                                                
Out[122]: 
array([[0.81792002, 0.        , 0.        ],
       [0.47090337, 0.        , 0.        ],
       [0.20433628, 0.        , 0.        ],
       [0.66201335, 0.        , 0.        ]])

但是,如果你生成了一个不同的随机数组:

In [124]: arr[:,0] = np.random.rand(4,1)                                                                     
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-124-86b2b8982a84> in <module>
----> 1 arr[:,0] = np.random.rand(4,1)

ValueError: could not broadcast input array from shape (4,1) into shape (4)

arr[:,0] 产生一维数组;标量索引会减少维度。 MATLAB 也这样做 - 使用 3d 或更高版本(但它具有 2d 下限)。

尝试将 (n,1) 数组放入 (n,) 槽时会产生错误。广播规则可以添加前导维度,但尾随维度必须是明确的。在numpy 中,前导维度是外部维度(MATLAB 的反向)。所以(n,) 可以广播到(1,n)

使用列表或数组进行索引会保留维度,因此这会将 (4,1) 放入 (4,1):

arr[:,[0]] = np.random.rand(4,1) 

而 (3,) 适合 (1,3):

arr[[0],:] = np.random.rand(3)  

A (1,n) 也适合 (n,):

arr[:,0] = np.random.rand(1,4) 

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 2015-08-07
    • 2023-03-31
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2015-08-20
    • 2014-08-30
    相关资源
    最近更新 更多