Is there a better way to use numpy in that case?

Question:

My output looks like that, but isn’t my code bad practice? Is there a way to replace the for with numpy functions?

[[ 1.   1.5  2.   2.5  3. ]
 [ 3.5  4.   4.5  5.   5.5]
 [ 6.   6.5  7.   7.5  8. ]
 [ 8.5  9.   9.5 10.  10.5]
 [11.  11.5 12.  12.5 13. ]
 [13.5 14.  14.5 15.  15.5]
 [16.  16.5 17.  17.5 18. ]
 [18.5 19.  19.5 20.  20.5]]
import numpy as np

list = []
x = 0.5

for i in range(8):
    temp = []
    list.append(temp)
    for j in range(5):
        x += 0.5
        temp.append(x)


array = np.array(list)
Asked By: soosius

||

Answers:

Not necessarily bad practice (except for calling your variable list) but it can be improved significanty by using np.arange as follows:

arr = np.arange(1,21,0.5).reshape((8,5))
Answered By: Ftagliacarne

You should not use a loop with numpy, but rather vectorial code.

You seem to want numpy.arange combined with reshape:

n, m = 8, 5
start = 0.5
step = 0.5

out = np.arange(start+step, start+step*(n*m+1), step).reshape(n, m)

Output:

array([[ 1. ,  1.5,  2. ,  2.5,  3. ],
       [ 3.5,  4. ,  4.5,  5. ,  5.5],
       [ 6. ,  6.5,  7. ,  7.5,  8. ],
       [ 8.5,  9. ,  9.5, 10. , 10.5],
       [11. , 11.5, 12. , 12.5, 13. ],
       [13.5, 14. , 14.5, 15. , 15.5],
       [16. , 16.5, 17. , 17.5, 18. ],
       [18.5, 19. , 19.5, 20. , 20.5]])
Answered By: mozway

First you initiallize the array with np.zeros with the final size. Then you select each position to assign x.

import numpy as np
x = 0.5

array = np.zeros((8,5))
for i in range(8):
    for j in range(5):
        x += 0.5
        array[i,j] = x
Answered By: Victor

You should use np.arange like other answers have pointed out. But you can also use normal python range.

np.array([*range(10, 41*5+1, 5)]).reshape(8,5) / 10
Answered By: IAmParadox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.