簡體   English   中英

替換多維數組的元素

[英]Replacing elements of a multidimensional array

我試圖用列表中的元素替換29 x 1矩陣的某些元素。

import numpy as np

initAmount = np.array([[0 for i in range(29)]])
initialAmount = np.ndarray.transpose(initAmount)
ind = [0.04, 0.02, 0.03]
#ind = [1,2,3]
initialAmount[0,0] = float(ind[0])
initialAmount[1,0] = float(ind[1])
initialAmount[2,0] = float(ind[2])
print(initialAmount)

不幸的是,這無法正常工作。 運行代碼后的initialAmount應該為[[0.04],[0.02],[0.03],[0],...],而不是[[0],[0],[0] ....],其中是我得到的結果。 當我的清單ind = [1,2,3]時,代碼可以正常工作。 因此,我假設精度存在錯誤,但是我不知道如何解決。

任何幫助將不勝感激。

只是讓你全光照陣列內置的numpy.zeros這需要一個dtypeshape參數,大大simplifyying你要完成的任務:

>>> init = np.zeros((29, 1), dtype=float)
>>> ind = [0.04, 0.02, 0.03]
>>> init[0,0] = ind[0]
>>> init[1,0] = ind[1]
>>> init[2,0] = ind[2]
>>> init
array([[ 0.04],
       [ 0.02],
       [ 0.03],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ],
       [ 0.  ]])
>>>

注意,默認情況下np.zeros使用float np.zeros 但是明確表示並沒有什么害處。

暫無
暫無

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

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