Python – Create 2d Array in Python Using For Loop Results

arrayspython

I run some code within a for loop. I want to take the results from my loop and place them in a 2d array with 2 columns and as many rows as times I iterate the loop. Here's a simplified version of what I have:

 for i in range(10):

      'bunch of stuff'

      centerx = xc
      centery = yc

How can I save my values for centerx and centery in a 2d array with 2 columns and 10 rows? Any help is appreciated, thanks!

Best Answer

You can try this:

import numpy as np
listvals = []
for i in range(10):
    listvals.append((xc, yc))
mat_vals = np.vstack(listvals)

This will output an ndarray like this:

[[ 2  0]
 [ 3  1]
 [ 4  2]
 [ 5  3]
 [ 6  4]
 [ 7  5]
 [ 8  6]
 [ 9  7]
 [10  8]
 [11  9]]

Or this maybe is better:

import numpy as np
list_xc = []
list_yc = []
for i in np.arange(10): 
    list_xc.append(xc)
    list_yc.append(yc)
mat_xc = np.asarray(list_xc)
mat_yc = np.asarray(list_yc)
mat_f = np.column_stack((mat_xc, mat_yc))