Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map python array into a x times longer array using each element x times

Tags:

python

list

numpy

I want to map a list or array into an array in python 3.x, input a [a,b,c] and get result like [a*2, a*2+1, b*2, b*2+1, c*2, c*2+1] e.g:

a = np.array([2,4,6])
result = []
for a1,a2 in zip(a*2, a*2+1):
    result = result + [a1,a2]
print(result)
# Output: [4, 5, 8, 9, 12, 13] 

There must be better ways. Both list and numpy solutions will be ok. Thanks

like image 958
Echan Avatar asked Nov 29 '18 11:11

Echan


2 Answers

One way to do that:

import numpy as np

a = np.array([2, 4, 6])
b = np.repeat(2 * a, 2)
b[1::2] += 1
print(b)
# [ 4  5  8  9 12 13]

Another way:

b = np.stack([2 * a, 2 * a + 1], axis=1).ravel()

EDIT:

If you want a solution that allows you to enlarge the array by any factor, not just 2, you can use a function like this:

import numpy as np

def make_longer(a, n):
    b = np.tile(n * a[:, np.newaxis], (1, n))
    b += np.arange(n, dtype=b.dtype)
    return b.ravel()

a = np.array([2, 4, 6])
print(make_longer(a, 2))
# [ 4  5  8  9 12 13]
print(make_longer(a, 3))
# [ 6  7  8 12 13 14 18 19 20]
like image 86
jdehesa Avatar answered Sep 21 '22 05:09

jdehesa


You can try;

In [1]: a = [2, 4, 6]

In [2]: f1 = lambda x: x*2

In [3]: f2 = lambda x:x*2+1

In [4]: [f(x) for x in a for f in (f1, f2)]
Out[4]: [4, 5, 8, 9, 12, 13]

or for one liner

In [4]: [f(i) for i in a for f in (lambda x: x*2, lambda x: x*2+1)]
Out[4]: [4, 5, 8, 9, 12, 13]
like image 45
Praveen Avatar answered Sep 21 '22 05:09

Praveen