1

I have an array A = np.array([1.43, 5.12, 2.67]) I want to make a multidimensional array named B from array A using np.repeat like this

B =np.repeat(A, 4)

and the result show like this:

B = [1.43, 1.43, 1.43, 1.43, 5.12, 5.12, 5.12, 5.12, 2.67, 2.67, 2.67, 2.67)

But i want the result shown like this:

B = ([1. 43, 1.43, 1.43, 1.43],
[5.12, 5.12, 5.12, 5.12],
[2.67, 2.67, 2.67, 2.67])

What should I do to get the result like that?

3
  • 2
    Try this : np.tile(A, (3,1)).T or np.repeat(A, 3).reshape(3,-1) Commented Sep 2, 2022 at 16:47
  • 2
    You can avoid a copy by broadcasting: np.broadcast_to(A[:, None], (A.shape[0], 4)) Commented Sep 2, 2022 at 16:55
  • If you make A a (3,1) shape, you can apply repeat to the last aixs: np.repeat(A,4, axis=1) Commented Sep 2, 2022 at 20:02

1 Answer 1

1

You can reshape the output array to achieve the desired format.

import numpy as np

A = np.array([1.43, 5.12, 2.67])
B = np.repeat(A, 4).reshape(3, -1)
print(B)

Output

[[1.43 1.43 1.43 1.43]
 [5.12 5.12 5.12 5.12]
 [2.67 2.67 2.67 2.67]]
Sign up to request clarification or add additional context in comments.

2 Comments

I want to ask again. We can call the elements of array B using print(B[0]) for call rows 1 of B. But is it possible for us to call the elements of each line? Because even though the value of each row is the same, each row will be given a different multiplier
For example, for the first row of B, the first 1.43 will multiplied by 2, and the second 1.43 will multiplied by 3, and the last one will multiplied by 4. is this possible to do? thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.