简体   繁体   English

替换多维数组的元素

[英]Replacing elements of a multidimensional array

I am trying to replace some elements of a 29 x 1 matrix with elements from a list. 我试图用列表中的元素替换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)

Unfortunately, this is not working like it is supposed to. 不幸的是,这无法正常工作。 initialAmount after running the code should be [[0.04],[0.02],[0.03],[0],...], and not [[0],[0],[0]....], which is the result I am getting. 运行代码后的initialAmount应该为[[0.04],[0.02],[0.03],[0],...],而不是[[0],[0],[0] ....],其中是我得到的结果。 The code works fine when my list ind = [1,2,3]. 当我的清单ind = [1,2,3]时,代码可以正常工作。 So, I am assuming there is an error with the precision, but I have no idea how to fix this. 因此,我假设精度存在错误,但是我不知道如何解决。

Any help will be appreciated. 任何帮助将不胜感激。

Just make your array usin the built-in numpy.zeros which takes a dtype and shape parameter, greatly simplifyying what you are trying to accomplish: 只是让你全光照阵列内置的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.  ]])
>>>

Note, by default np.zeros using float dtype. 注意,默认情况下np.zeros使用float np.zeros But it doesn't hurt to be explicit. 但是明确表示并没有什么害处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM