0

Given a list of points I would like to create a numpy array with coordinates. Related questions are here and here. Does anyone know the correct or a more efficient way of doing this?

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()
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Robert Altena
  • 787
  • 2
  • 11
  • 26
  • First of all, `x` and `y` are static properties of `Point`. What you want is to define a `__init__(self, x, y)` function in `Point` and do `self.x = x; self.y = y`, which makes `x` and `y` belong to _a_ `Point`, not the `Point` _class_. – hyper-neutrino Oct 27 '17 at 02:11
  • That is just to set up the sample. I am given a list of objects that have proper x and y properties, The question is how to get to a numpy array from the python list. – Robert Altena Oct 27 '17 at 02:13
  • 1
    Okay. You could just replace the last three lines with this: `arr = np.vstack(zip((p.x for p in points), (p.y for p in points)))` – hyper-neutrino Oct 27 '17 at 02:18
  • Honestly you could set up the entire thing like this: https://tio.run/##bY/BagMxDETP8VfoaIMxG0Ivhf5D7yUYk3gT011ZWE5Yf/3Gu06aQHOTmDczEpV8jrib5zBSTBnwMlIBx4AkxGFwzPAdA@ZPsTn6HqwNGLK1kv3Qa5g0FFWlzbKaCb5geiylLqWZTj7baXWsbPL5khCa5UmU98Q9g/8yauu/ygdR7sTLUe0OQcsTXOefvRB9TBAgICSHJy@33YI3wjgij0e5Pl0V02n4MJ1SQriUqh/JXDm7w6@UQ@AsR0cNNuubGlqOUhre6OWpK2Vy7WeK7GWNp7Q01hI1zzc – hyper-neutrino Oct 27 '17 at 02:20
  • Thank you. That is very kind of you. I should have clarified in the question that I have no control over the Point class. – Robert Altena Oct 27 '17 at 02:22
  • No worries. And oh, okay. If that's the case, ignore my last comment and just swap out the last three lines then. :) – hyper-neutrino Oct 27 '17 at 02:22

1 Answers1

2

grab both x, y at once, sitck in list in a listcomp and it has the structure you want

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.]])
f5r5e5d
  • 3,656
  • 3
  • 14
  • 18