initialize a numpy array

前端 未结 12 1719
情歌与酒
情歌与酒 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:28

    The way I usually do that is by creating a regular list, then append my stuff into it, and finally transform the list to a numpy array as follows :

    import numpy as np
    big_array = [] #  empty regular list
    for i in range(5):
        arr = i*np.ones((2,4)) # for instance
        big_array.append(arr)
    big_np_array = np.array(big_array)  # transformed to a numpy array
    

    of course your final object takes twice the space in the memory at the creation step, but appending on python list is very fast, and creation using np.array() also.

提交回复
热议问题