簡體   English   中英

Numpy:ValueError:無法將輸入數組從形狀(4,1)廣播到形狀(4)

[英]Numpy: ValueError: could not broadcast input array from shape (4,1) into shape (4)

我正在使用 Python 3.7 和 numpy 1.18.3。 我有一個包含 4 行的數組。 我需要定期添加一個新列。 每次我向數組添加一個新條目時,它都被定義為 4,1 數組 (t)。

我偶爾會檢查 bin 是否可以容納分配(下面的 d_entry),是否必須從 bin 中減去分配並更新列。

導入 numpy 作為 np

t = 4x1 numpy array [[  150], [50000], [30000], [20000]]
d_entry = 4x1 numpy array [[2.6000e+01], [1.1638e+04], [5.0000e+00], [9.8290e+03]]

new_bin = np.subtract(t, d_entry)
bin_space =  np.append(bin_space, new_bin, axis=1)

因此,例如,有兩個 bin 條目,我的 bin_space 最終看起來像:

[[  107.   124.], [27798. 38362.], [29992. 29995.], [ 9401. 10171.]]

如前所述,bin 空間條目(列)有時需要更新,用更新的 4 x 1 列替換條目。

為此,我像這樣引用 bin_space 列:

space_left = np.array(bin_space[:,j])   

(PyCharm 說現在是 (4,) - 而不是 4,1

bin_space[:,j] = np.subtract(space_left, d_entry)**

然后我以錯誤告終。 我不確定如何讓數組提取相同的類型。

回溯(最后一次調用):文件“D:/Development/oasg-apps/src/mcl/python/mcl_bin_packing.py”,第 398 行,在 main() 文件“D:/Development/oasg-apps/src/ mcl/python/mcl_bin_packing.py”,第 247 行,主要 n_bins、bin_for_item、bin_space = allocate_ffd(d_vectors, t_resource, num_metrics_types) 文件“D:/Development/oasg-apps/src/mcl/python/mcl_bin_packing.py”,第 135 行,在 allocate_ffd bin_space[:,j] = np.subtract(space_left, d_entry) ValueError: could not broadcast input array from shape (4,1) into shape (4)

這重現了該問題,但“無法將輸入數組從形狀(2,1)廣播到形狀(2)”:

import numpy as np

bin_space = np.array([0, 0])
bin_space = np.reshape(bin_space, (2,1))

# Shape our target resources into a numpy array.
target_resource = np.array([150, 50000])
target_resource = np.reshape(target_resource,(2,1))

new_resource = np.array([10, 200])
new_resource = np.reshape(new_resource,(2,1))

bin_space = np.append(bin_space, target_resource, axis=1)
bin_space = np.append(bin_space, target_resource, axis=1)

bin_space[:,1] =  new_resource

任何幫助表示贊賞。

謝謝,

克萊夫

任何一個:

bin_space[:,1] = new_resource.T

或者:

bin_space[:,1] = new_resource.flatten()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM