Repeat each value of an array two times (numpy)

前端 未结 3 1867
长发绾君心
长发绾君心 2021-01-15 15:49

Let A be a numpy array like :

A = np.array([1, 2, 3, 4, 5])

I want to find the cleaner way to produce a new array with each v

3条回答
  •  花落未央
    2021-01-15 16:16

    If you need to do this operation in a time critical region, the following code is the fastest (using Numpy 1.9 development version):

    In [1]: A = numpy.array([1, 2, 3, 4, 5]*1000) 
    In [2]: %timeit numpy.array([A, A]).T.ravel('F')
    100000 loops, best of 3: 6.44 µs per loop
    

    Note that flatten would make an additional copy, so ravel should be used instead.

    If you prefer readability, the column_stack and repeat functions are better:

    In [3]: %timeit numpy.column_stack((A, A)).ravel()
    100000 loops, best of 3: 15.4 µs per loop
    
    In [4]: timeit numpy.repeat(A, 2)
    10000 loops, best of 3: 53.9 µs per loop
    

提交回复
热议问题