Most efficient way to reverse a numpy array

后端 未结 7 742
南旧
南旧 2020-11-30 16:43

Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the com

7条回答
  •  忘掉有多难
    2020-11-30 17:27

    I will expand on the earlier answer about np.fliplr(). Here is some code that demonstrates constructing a 1d array, transforming it into a 2d array, flipping it, then converting back into a 1d array. time.clock() will be used to keep time, which is presented in terms of seconds.

    import time
    import numpy as np
    
    start = time.clock()
    x = np.array(range(3))
    #transform to 2d
    x = np.atleast_2d(x)
    #flip array
    x = np.fliplr(x)
    #take first (and only) element
    x = x[0]
    #print x
    end = time.clock()
    print end-start
    

    With print statement uncommented:

    [2 1 0]
    0.00203907123594
    

    With print statement commented out:

    5.59799927506e-05
    

    So, in terms of efficiency, I think that's decent. For those of you that love to do it in one line, here is that form.

    np.fliplr(np.atleast_2d(np.array(range(3))))[0]
    

提交回复
热议问题