Home > Back-end >  Is there a better way to use numpy in that case?
Is there a better way to use numpy in that case?

Time:11-22

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)

CodePudding user response:

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))

CodePudding user response:

You would 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]])

CodePudding user response:

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

CodePudding user response:

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
  • Related