0

I have a float list:

[1.0, 2.0, 3.0, 4.0] 

How can I reshape this list into a multi-dimensional array like:

[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0], [3.0, 3.0, 3.0], [4.0, 4.0 ,4.0]]

without using a loop? Is it possible using numpy or any other?

1
  • Use np.broadcast_to(arr[:, None], (4, 3)). Much better than repeat. I'll find the dupe Mar 13, 2020 at 21:41

2 Answers 2

6

If you start with a NumPy array, you can use numpy.repeat() and then reshape() to get the array size/shape you want:

> import numpy as np

> a = np.array([1.0, 2.0, 3.0, 4.0])

> np.repeat(a, 3).reshape(-1, 3) 

array([[1., 1., 1.],
       [2., 2., 2.],
       [3., 3., 3.],
       [4., 4., 4.]])
1

If you can survive not using numpy:

orig = [1.0, 2.0, 3.0, 4.0]
N = 3
matrix = [[n]*N for n in orig]

Not the answer you're looking for? Browse other questions tagged or ask your own question.