Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy numpy array efficiently

Suppose I have a Nx3 array A, and another empty MxNx3 array B. I want to copy the values from A to B such that those sets of values appear M times in B. How to do this efficiently other than using a loop?

like image 937
Physicist Avatar asked Aug 01 '26 21:08

Physicist


2 Answers

You can write b[:] = a and let broadcasting take over. For example:

>>> a = np.arange(6).reshape(2, 3)
>>> b = np.zeros((3, 2, 3))
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> b
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],
       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],
       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

Then to copy a into b:

>>> b[:] = a
>>> b
array([[[ 0.,  1.,  2.],
        [ 3.,  4.,  5.]],
       [[ 0.,  1.,  2.],
        [ 3.,  4.,  5.]],
       [[ 0.,  1.,  2.],
        [ 3.,  4.,  5.]]])

Note that b has to be able to hold the datatype of a. If a was an array of complex numbers, the imaginary part would be lost when copying to b (because it can only hold float values).

like image 93
Alex Riley Avatar answered Aug 03 '26 13:08

Alex Riley


You also could write: suppose your array a is numpy array

    ans = numpy.array([a.tolist()*M])
like image 35
Chung-Yen Hung Avatar answered Aug 03 '26 12:08

Chung-Yen Hung