Repeating array with transformation

Viewed 305

How can I repeat the following example sequence:

l = np.array([3,4,5,6,7])

Up to n times, doubling the values on each repetition. So for n=3:

[3, 4, 5, 6, 7, 6,  8, 10, 12, 14, 12, 16, 20, 24, 28]

Is there a simple way avoiding loops with numpy perhaps?

7 Answers

numpy.outer + numpy.ndarray.ravel:

>>> a = np.array([3,4,5,6,7])                                                                                          
>>> n = 3                                                                                                              
>>> factors = 2**np.arange(n)                                                                                          
>>> np.outer(factors, a).ravel()                                                                                       
array([ 3,  4,  5,  6,  7,  6,  8, 10, 12, 14, 12, 16, 20, 24, 28])

Details:

>>> factors                                                                                                            
array([1, 2, 4])
>>> np.outer(factors, a)                                                                                               
array([[ 3,  4,  5,  6,  7], # 1*a
       [ 6,  8, 10, 12, 14], # 2*a
       [12, 16, 20, 24, 28]]) # 4*a

You can use concatenate and list comprehension using powers of 2 as the multiplicative factor. Here 3 is the number of repetitions you need.

l = np.array([3,4,5,6,7])
final = np.concatenate([l*2**(i) for i in range(3)])
print (final)

array([ 3,  4,  5,  6,  7,  6,  8, 10, 12, 14, 12, 16, 20, 24, 28])

Here is one way:

>>> (l * [[1], [2], [4]]).flatten()
array([ 3,  4,  5,  6,  7,  6,  8, 10, 12, 14, 12, 16, 20, 24, 28])

(Only works if you want multiples of the input.)

You could do:

import numpy as np

l = np.array([3, 4, 5, 6, 7])

rows = np.tile(l, 3).reshape(-1, len(l)) * np.power(2, np.arange(3)).reshape(-1, 1)
print(rows.flatten())

Output

[ 3  4  5  6  7  6  8 10 12 14 12 16 20 24 28]

You can use np.power with np.ndarray.ravel:

A = np.array([3,4,5,6,7])

res = (A * np.power(2, np.arange(3))[:, None]).ravel()

print(res)

array([ 3,  4,  5,  6,  7,  6,  8, 10, 12, 14, 12, 16, 20, 24, 28])

You can to loop over n, and concatenate a new list each time:

l = [3,4,5,6,7]
n = 3
new_l = []
for i in range(n):
    new_l += [j*2**i for j in l]
new_l = np.array(new_l)

Output

array([3, 4, 5, 6, 7, 6, 8, 10, 12, 14, 12, 16, 20, 24, 28])

You can do that in pure python using list comprehensions:

l = [3,4,5,6,7]

n     = 3
mult  = [1 * 2**i for i in range(n)]
final = list([x*m for m in mult for x in l])
Related