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?

Tomerikoo
  • 15,737
  • 15
  • 35
  • 52
Harisreedhar
  • 153
  • 4

2 Answers2

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.]])
Mark
  • 84,957
  • 6
  • 91
  • 136
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]
tevemadar
  • 11,284
  • 3
  • 17
  • 44