Home > Enterprise >  appending values to coordinates in array of zeros
appending values to coordinates in array of zeros

Time:10-22

I am generating two parameters e.g.

s1 = [0, 0.25, 0.5, 0.75, 1.0]
s2 = [0, 0.25, 0.5, 0.75, 1.0]

based on dimensions of both these lists above, i am creating a grid of zeros:

np.zeros((5,5))

I then pair up each of the numbers in each list so they form coordinate locations in my empty grid e.g. (0,0), (0,0.25), (0,0.5) etc. (25 combinations to fit into 5x5 grid).

my issue is i am not too sure how to append values into the grid based on each of the coordinates generated. e.g. if i want to append the number 5 to grid location (0,0) etc so the grid fills up.

Any help is greatly appreciated.

CodePudding user response:

not sure it is fastest way to get it, check if the output is what you were expecting

import numpy as np

s1 = [0, 0.25, 0.5, 0.75, 1.0]
s2 = [0, 0.25, 0.5, 0.75, 1.0]



arr = np.zeros((5,5,2), dtype=float)

print (arr.shape,  arr.size, arr.ndim)


for i in range(len(s1)):
    for j in range(len(s2)):
        arr[i,j] = s1[i], s2[j]
        
        
print(arr)

output :

(5, 5, 2) 50 3

[[[0.   0.  ]
  [0.   0.25]
  [0.   0.5 ]
  [0.   0.75]
  [0.   1.  ]]

 [[0.25 0.  ]
  [0.25 0.25]
  [0.25 0.5 ]
  [0.25 0.75]
  [0.25 1.  ]]

 [[0.5  0.  ]
  [0.5  0.25]
  [0.5  0.5 ]
  [0.5  0.75]
  [0.5  1.  ]]

 [[0.75 0.  ]
  [0.75 0.25]
  [0.75 0.5 ]
  [0.75 0.75]
  [0.75 1.  ]]

 [[1.   0.  ]
  [1.   0.25]
  [1.   0.5 ]
  [1.   0.75]
  [1.   1.  ]]]

CodePudding user response:

The easiest way is probably to construct a meshgrid and transpose it so that the axises are the way you want them:

np.array(np.meshgrid(s1, s2)).transpose(1, 2, 0)
  • Related