Flattening a list of NumPy arrays?

前端 未结 5 1592
别那么骄傲
别那么骄傲 2020-12-01 06:13

It appears that I have data in the format of a list of NumPy arrays (type() = np.ndarray):

[array([[ 0.00353654]]), array([[ 0.00353654]]), arra         


        
5条回答
  •  攒了一身酷
    2020-12-01 06:31

    You could use numpy.concatenate, which as the name suggests, basically concatenates all the elements of such an input list into a single NumPy array, like so -

    import numpy as np
    out = np.concatenate(input_list).ravel()
    

    If you wish the final output to be a list, you can extend the solution, like so -

    out = np.concatenate(input_list).ravel().tolist()
    

    Sample run -

    In [24]: input_list
    Out[24]: 
    [array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]]),
     array([[ 0.00353654]])]
    
    In [25]: np.concatenate(input_list).ravel()
    Out[25]: 
    array([ 0.00353654,  0.00353654,  0.00353654,  0.00353654,  0.00353654,
            0.00353654,  0.00353654,  0.00353654,  0.00353654,  0.00353654,
            0.00353654,  0.00353654,  0.00353654])
    

    Convert to list -

    In [26]: np.concatenate(input_list).ravel().tolist()
    Out[26]: 
    [0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654,
     0.00353654]
    

提交回复
热议问题