Python 替换多维数组的元素

Python 替换多维数组的元素,python,numpy,multidimensional-array,Python,Numpy,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

我试图用列表中的元素替换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]…],这是我得到的结果。当我的list ind=[1,2,3]时,代码工作正常。所以,我假设精度有误差,但我不知道如何修正


任何帮助都将不胜感激。

只需使用内置的
numpy.zero
来制作数组,该数组采用
dtype
shape
参数,大大简化了您要完成的任务:

>>> 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.  ]])
>>>

注意,默认情况下,使用float-dtype
np.zero
。但直言不讳也无妨

只需在第一步指定数据类型:
np.array([[0代表范围内的i(29)],dtype=float)
@Divakar,这是一个很容易解决的问题!我现在觉得自己很愚蠢。谢谢。