Skip to content Skip to sidebar Skip to footer

Repeat Each Value Of An Array Two Times (numpy)

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 value repeated two times: B = np.array([1, 1, 2, 2, 3,

Solution 1:

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])

Solution 2:

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     

Solution 3:

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

Post a Comment for "Repeat Each Value Of An Array Two Times (numpy)"