从点列表中创建一个numpy坐标数组

时间:2017-10-27 02:04:49

标签: python numpy

给定一个点列表,我想创建一个带坐标的numpy数组。相关问题为herehere。有谁知道正确或更有效的方法吗?

import numpy as np

# Please note that we have no control over the point class.
# This code just to generate the example.
class Point:
    x = 0.0
    y = 0.0


points = list()
for i in range(10):
    p = Point()
    p.x = 10.0
    p.y = 5.0
    points.append(p)

# The question starts here.
# The best I could come up with so far:
x = np.fromiter((p.x for p in points), float)
y = np.fromiter((p.y for p in points), float)
arr = np.vstack((x,y)).transpose()

1 个答案:

答案 0 :(得分:1)

同时抓住x,y,在listcomp中列表并且它具有你想要的结构

np.array([[e.x, e.y] for e in points])  

Out[203]: 
array([[ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.],
       [ 10.,   5.]])