Move the numpy array with you

I have an N x 2 dimensional matrix. I would like to make (2 * N) x 2 where each column is repeated. I am curious if there is a more efficient way than what I wrote below to accomplish this task.

>>> a = np.array([[1,2,3,4], [2,4,6,8]]) >>> b = np.array(zip(aT,aT)) >>> b.shape = (2*len(a[0]), 2) >>> bT array([[1, 1, 2, 2, 3, 3, 4, 4], [2, 2, 4, 4, 6, 6, 8, 8]]) 

The code above is slow by the numpy standard, most likely due to zip . Is there a numpy function that I can replace zip with? Or is the best way to do this at all?

+4
source share
1 answer

You can use repeat :

 import numpy as np def slow(a): b = np.array(zip(aT,aT)) b.shape = (2*len(a[0]), 2) return bT def fast(a): return a.repeat(2).reshape(2, 2*len(a[0])) def faster(a): # compliments of WW return a.repeat(2, axis=1) 

gives

 In [42]: a = np.array([[1,2,3,4],[2,4,6,8]]) In [43]: timeit slow(a) 10000 loops, best of 3: 59.4 us per loop In [44]: timeit fast(a) 100000 loops, best of 3: 4.94 us per loop In [45]: a = np.arange(100).reshape(2, 50) In [46]: timeit slow(a) 1000 loops, best of 3: 489 us per loop In [47]: timeit fast(a) 100000 loops, best of 3: 6.7 us per loop 

[update]:

 In [101]: timeit faster(a) 100000 loops, best of 3: 4.4 us per loop 
+6
source

Source: https://habr.com/ru/post/1433900/


All Articles