简体   繁体   English

将点列表转换为numpy 2D数组

[英]Converting a list of points to a numpy 2D array

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): 我正在使用genfromtxt来导入一个二维数组,该数组的所有值都列在表单的文本文件中(x和y是整数):

    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. 我正在使用下面的for循环,但我很确定必须采用一行方式来实现它。 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]

You can replace the for loop with the following: 您可以使用以下内容替换for循环:

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

Z[xidx, yidx] = raw[:,2]

You could also go with numpy.searchsorted which will also allow for non-equally spaced / float data: 你也可以使用numpy.searchsorted ,它也允许非等间距/浮点数据:

raw = genfromtxt(file,skip_header = 6)

xvalues = numpy.sorted(set(raw[:,0]))
xidx = numpy.searchsorted(xvalues, raw[:,0])

yvalues = numpy.sorted(set(raw[:,1]))
yidx = numpy.searchsorted(yvalues, raw[:,1])

Z = numpy.zeros((len(xvalues), len(yvalues)))
Z[xidx, yidx] = raw[:,2]

Otherwise, I would be following Simon's answer. 否则,我会关注西蒙的回答。

To import a matrix from a file you can just split the lines and then convert to int. 要从文件导入矩阵,您只需拆分行然后转换为int。

[[int(i) for i in j.split()] for j in open('myfile').readlines()]

of course, I'm supposing your file contains only the matrix. 当然,我假设你的文件只包含矩阵。

At the end, you can convert this 2-D array to numpy. 最后,您可以将此二维数组转换为numpy。

You may try something like this: 你可以尝试这样的事情:

>>> Z = zeros((3, 3))
>>> test = array([[0, 1, 2], [1, 1, 6], [2, 0, 4]])
>>> Z[test[:, 0:2].T.tolist()]
array([ 0.,  0.,  0.])
>>> Z[test[:, 0:2].T.tolist()] = test[:, 2]
>>> Z
array([[ 0.,  2.,  0.],
       [ 0.,  6.,  0.],
       [ 4.,  0.,  0.]])

In your case: 在你的情况下:

Z[(raw[:, 0:2] - minimum(raw[:, 0:2], axis=0)).T.tolist()] = raw[:, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM