Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy duplicate elements

maybe this is a easy question, but is there a fast way to duplicate elements in a array? It should work like this way for 3D:

1 2 3
4 5 6
7 8 9

1 1 2 2 3 3
1 1 2 2 3 3
4 4 5 5 6 6
4 4 5 5 6 6
7 7 8 8 9 9
7 7 8 8 9 9

I tried it with 3 nested for-loops, but this was really slow.

like image 964
Christian Avatar asked Dec 20 '12 09:12

Christian


People also ask

How do I duplicate in NumPy?

Use numpy. copy() function to copy Python NumPy array (ndarray) to another array. This method takes the array you wanted to copy as an argument and returns an array copy of the given object. The copy owns the data and any changes made to the copy will not affect the original array.

How do you repeat an element in a NumPy array?

NumPy: repeat() function The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

How does NP repeat work?

The np. repeat function repeats the individual elements of an input array. But np. tile will take the entire array – including the order of the individual elements – and copy it in a particular direction.


1 Answers

>>> a = np.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
>>> np.repeat(np.repeat(a, 2, 0), 2, 1)

array([[1, 1, 2, 2, 3, 3],
       [1, 1, 2, 2, 3, 3],
       [4, 4, 5, 5, 6, 6],
       [4, 4, 5, 5, 6, 6],
       [7, 7, 8, 8, 9, 9],
       [7, 7, 8, 8, 9, 9]])
like image 161
eumiro Avatar answered Oct 04 '22 13:10

eumiro