Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list of points to a numpy 2D array

Tags:

python

numpy

I'm using genfromtxt to import essentially a 2D array that has all its values listed in a text file of the form (x's and y's are integers):

    x1   y1   z1
    x2   y2   z2
    :    :    :

I'm using the for loop below but I'm pretty sure there must be a one line way to do it. What would be a more efficient way to do this conversion?

raw = genfromtxt(file,skip_header = 6)

xrange = ( raw[:,0].min() , raw[:,0].max() )
yrange = ( raw[:,1].min() , raw[:,1].max() )

Z = zeros(( xrange[1] - xrange[0] +1 , yrange[1] - yrange[0] +1 ))

for row in raw:
    Z[ row[0]-xrange[0] , row[1]-yrange[0] ] = row[2]
like image 923
foglerit Avatar asked May 18 '11 15:05

foglerit


1 Answers

You can replace the for loop with the following:

xidx = (raw[:,0]-xrange[0]).astype(int)
yidx = (raw[:,1]-yrange[0]).astype(int)

Z[xidx, yidx] = raw[:,2]
like image 189
joris Avatar answered Nov 14 '22 23:11

joris