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?
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).
You also could write: suppose your array a is numpy array
ans = numpy.array([a.tolist()*M])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With