Pythonic way to create a numpy array from a list of numpy arrays

后端 未结 6 1084
执笔经年
执笔经年 2020-12-13 06:24

I generate a list of one dimensional numpy arrays in a loop and later convert this list to a 2d numpy array. I would\'ve preallocated a 2d numpy array if i knew the number o

6条回答
  •  悲哀的现实
    2020-12-13 06:43

    Convenient way, using numpy.concatenate. I believe it's also faster, than @unutbu's answer:

    In [32]: import numpy as np 
    
    In [33]: list_of_arrays = list(map(lambda x: x * np.ones(2), range(5)))
    
    In [34]: list_of_arrays
    Out[34]: 
    [array([ 0.,  0.]),
     array([ 1.,  1.]),
     array([ 2.,  2.]),
     array([ 3.,  3.]),
     array([ 4.,  4.])]
    
    In [37]: shape = list(list_of_arrays[0].shape)
    
    In [38]: shape
    Out[38]: [2]
    
    In [39]: shape[:0] = [len(list_of_arrays)]
    
    In [40]: shape
    Out[40]: [5, 2]
    
    In [41]: arr = np.concatenate(list_of_arrays).reshape(shape)
    
    In [42]: arr
    Out[42]: 
    array([[ 0.,  0.],
           [ 1.,  1.],
           [ 2.,  2.],
           [ 3.,  3.],
           [ 4.,  4.]])
    

提交回复
热议问题