Initialise numpy array of unknown length

前端 未结 5 1106
无人及你
无人及你 2020-12-02 08:38

I want to be able to \'build\' a numpy array on the fly, I do not know the size of this array in advance.

For example I want to do something like this:



        
相关标签:
5条回答
  • 2020-12-02 09:07

    For posterity, I think this is quicker:

    a = np.array([np.array(list()) for _ in y])
    

    You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.


    Responding to comment below:

    >>> import numpy as np
    >>> y = range(10)
    >>> a = np.array([np.array(list) for _ in y])
    >>> a
    array([array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object),
           array(<type 'list'>, dtype=object)], dtype=object)
    
    0 讨论(0)
  • 2020-12-02 09:13
    a = np.empty(0)
    for x in y:
        a = np.append(a, x)
    
    0 讨论(0)
  • 2020-12-02 09:15

    Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).

        a = []
        for x in y:
            a.append(x)
        a = np.array(a)
    
    0 讨论(0)
  • 2020-12-02 09:16

    You can do this:

    a = np.array([])
    for x in y:
        a = np.append(a, x)
    
    0 讨论(0)
  • 2020-12-02 09:30

    Since y is an iterable I really do not see why the calls to append:

    a = np.array(list(y))
    

    will do and it's much faster:

    import timeit
    
    print timeit.timeit('list(s)', 's=set(x for x in xrange(1000))')
    # 23.952975494633154
    
    print timeit.timeit("""li=[]
    for x in s: li.append(x)""", 's=set(x for x in xrange(1000))')
    # 189.3826994248866
    
    0 讨论(0)
提交回复
热议问题