【问题标题】:Create a numpy array of coordinates from a list of points从点列表创建一个 numpy 坐标数组
【发布时间】:2017-10-27 02:04:48
【问题描述】:

给定一个点列表,我想创建一个带有坐标的 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()

【问题讨论】:

  • 首先xyPoint的静态属性。您想要的是在Point 中定义一个__init__(self, x, y) 函数并执行self.x = x; self.y = y,这使得xy 属于a Point,而不是Point 类.
  • 这只是设置示例。我得到了一个具有适当 x 和 y 属性的对象列表,问题是如何从 python 列表中获取一个 numpy 数组。
  • 好的。您可以将最后三行替换为:arr = np.vstack(zip((p.x for p in points), (p.y for p in points)))
  • 老实说,您可以像这样设置整个事情:tio.run/##bY/BagMxDETP8VfoaIMxG0Ivhf5D7yUYk3gT011ZWE5Yf/…
  • 谢谢。你真是太好了。我应该在问题中澄清我无法控制 Point 类。

标签: python numpy


【解决方案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.]])

【讨论】:

  • 谢谢。这是一个非常优雅的代码行。赞赏。
猜你喜欢
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 2019-06-09
  • 2021-11-22
  • 1970-01-01
相关资源
最近更新 更多