Repeat each value of an array two times (numpy)

前端 未结 3 1868
长发绾君心
长发绾君心 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
    
    0 讨论(0)
  • 2021-01-15 16:26

    You can use numpy.column_stack and numpy.ndarray.flatten:

    In [12]: numpy.column_stack((A, A)).flatten()                                                    
    Out[12]: array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])
    

    Timing comparison:

    In [27]: A = numpy.array([1, 2, 3, 4, 5]*1000)                                                   
    
    In [28]: %timeit numpy.column_stack((A, A)).flatten()                                            
    10000 loops, best of 3: 44.7 µs per loop                                                         
    
    In [29]: %timeit numpy.repeat(A, 2)                                                              
    10000 loops, best of 3: 104 µs per loop                                                          
    
    In [30]: %timeit numpy.tile(A,2).reshape(2,-1).flatten('F')                                      
    10000 loops, best of 3: 129 µs per loop     
    
    0 讨论(0)
  • 2021-01-15 16:28

    Use repeat()

    In [1]: import numpy as np
    
    In [2]: A = np.array([1, 2, 3, 4, 5])
    
    In [3]: np.repeat(A,2)
    Out[3]: array([1, 1, 2, 2, 3, 3, 4, 4, 5, 5])
    
    0 讨论(0)
提交回复
热议问题