Flattening a list of NumPy arrays?

前端 未结 5 1595
别那么骄傲
别那么骄傲 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:44

    Another way using itertools for flattening the array:

    import itertools
    
    # Recreating array from question
    a = [np.array([[0.00353654]])] * 13
    
    # Make an iterator to yield items of the flattened list and create a list from that iterator
    flattened = list(itertools.chain.from_iterable(a))
    

    This solution should be very fast, see https://stackoverflow.com/a/408281/5993892 for more explanation.

    If the resulting data structure should be a numpy array instead, use numpy.fromiter() to exhaust the iterator into an array:

    # Make an iterator to yield items of the flattened list and create a numpy array from that iterator
    flattened_array = np.fromiter(itertools.chain.from_iterable(a), float)
    

    Docs for itertools.chain.from_iterable(): https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable

    Docs for numpy.fromiter(): https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html

提交回复
热议问题