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
  • 18,379
  • 16
  • 47
  • 61
Harisreedhar
  • 173
  • 1
  • 5

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
  • 90,562
  • 7
  • 108
  • 148
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
  • 12,389
  • 3
  • 21
  • 49