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()
6
  • 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. Commented Oct 27, 2017 at 2: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. Commented Oct 27, 2017 at 2: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))) Commented Oct 27, 2017 at 2:18
  • Honestly you could set up the entire thing like this: tio.run/##bY/BagMxDETP8VfoaIMxG0Ivhf5D7yUYk3gT011ZWE5Yf/… Commented Oct 27, 2017 at 2: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. Commented Oct 27, 2017 at 2:22

1 Answer 1

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.]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That is a very elegant looking line of code. Appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.