Repeating Each Element of a Numpy Array 5 Times

Repeating each element of a numpy array 5 times

In [1]: data = np.arange(-50,50,10)

To repeat each element 5 times use np.repeat:

In [3]: np.repeat(data, 5)
Out[3]:
array([-50, -50, -50, -50, -50, -40, -40, -40, -40, -40, -30, -30, -30,
-30, -30, -20, -20, -20, -20, -20, -10, -10, -10, -10, -10, 0,
0, 0, 0, 0, 10, 10, 10, 10, 10, 20, 20, 20, 20,
20, 30, 30, 30, 30, 30, 40, 40, 40, 40, 40])

To repeat the array 5 times use np.tile:

In [2]: np.tile(data, 5)
Out[2]:
array([-50, -40, -30, -20, -10, 0, 10, 20, 30, 40, -50, -40, -30,
-20, -10, 0, 10, 20, 30, 40, -50, -40, -30, -20, -10, 0,
10, 20, 30, 40, -50, -40, -30, -20, -10, 0, 10, 20, 30,
40, -50, -40, -30, -20, -10, 0, 10, 20, 30, 40])

Note, however, that sometimes you can take advantage of NumPy broadcasting instead of creating a larger array with repeated elements.

For example, if

z = np.array([1, 2])
v = np.array([[3], [4], [5]])

then to add these arrays to produce

 [[4 5]
[5 6]
[6 7]]

you do not need to use tile:

In [12]: np.tile(z, (3,1))
Out[12]:
array([[1, 2],
[1, 2],
[1, 2]])

In [13]: np.tile(v, (1,2))
Out[13]:
array([[3, 3],
[4, 4],
[5, 5]])

In [14]: np.tile(z, (3,1)) + np.tile(v, (1,2))
Out[14]:
array([[4, 5],
[5, 6],
[6, 7]])

Instead, NumPy will broadcast the arrays for you:

In [15]: z + v
Out[15]:
array([[4, 5],
[5, 6],
[6, 7]])

Repeat ndarray n times

Use np.tile

>>> a = np.array([True, True, False])
>>> np.tile(a, 3)
... array([ True, True, False, True, True, False, True, True, False])

Duplicate numpy Array Multiple times

You can use use numpy.repeat. It repeats array's elements by specifying repeat number:

new_arr = numpy.repeat(old_arr, 8)

How to repeat specific elements in numpy array?

a numpy solution. Use np.clip and np.repeat

n = 2
a = np.asarray([1,2,3,4,5])
cond = (a % 2) == 0 #condition is True on even numbers

m = np.repeat(a, np.clip(cond * n, a_min=1, a_max=None))

In [124]: m
Out[124]: array([1, 2, 2, 3, 4, 4, 5])

Or you may use numpy ndarray.clip instead of np.clip for shorter command

m = np.repeat(a, (cond * n).clip(min=1))

Repeat a list's elements in the same order

import numpy as np
s1 = [10,20]
s2 = np.array(s1).repeat(2)
print(list(s2)) # [10, 10, 20, 20]

I could not resist the urge to use numpy in such operations. With this function you can repeat not only for single dimensional cases but also in case of matrix or higher order tensors as well.

repeating a numpy array N times

This is what you want:

x=np.concatenate([my_input_array, my_input_array, my_input_array])
for i in x:
print(i)

Output:

-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456
-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456
-1.02295637
-0.60583836
-0.42240581
-0.78376377
-0.85821456


Related Topics



Leave a reply



Submit