initialize a numpy array

前端 未结 12 1721
情歌与酒
情歌与酒 2020-11-28 02:55

Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop,

12条回答
  •  我在风中等你
    2020-11-28 03:35

    I realize that this is a bit late, but I did not notice any of the other answers mentioning indexing into the empty array:

    big_array = numpy.empty(10, 4)
    for i in range(5):
        array_i = numpy.random.random(2, 4)
        big_array[2 * i:2 * (i + 1), :] = array_i
    

    This way, you preallocate the entire result array with numpy.empty and fill in the rows as you go using indexed assignment.

    It is perfectly safe to preallocate with empty instead of zeros in the example you gave since you are guaranteeing that the entire array will be filled with the chunks you generate.

提交回复
热议问题