3

I have a coordinates list looking like so

myCoordinates
> [(2, -6), (21, 19)]

I want to convert them into shapely geometry objects so that I can do some calculations with them:

from shapely.geometry import Point
for i in myCoordinates:
    c = [Point(i[0], i[1])]

print c
> [<shapely.geometry.point.Point object at 0x1044033d0>]

However, that only gives me one (!) geometry object.

But when I do this

circles = [Point(random.random(), random.random()).buffer(random.random() * 0.1) for i in range(3)]

I get three geometry objects.

print circles
> [<shapely.geometry.polygon.Polygon object at 0x1043f6890>, <shapely.geometry.polygon.Polygon object at 0x10442f8d0>, <shapely.geometry.polygon.Polygon object at 0x10442f910>]

What am I doing wrong? Why is it only converting one Point into a geometry object and not the two in my list?

four-eyes
  • 10,740
  • 29
  • 111
  • 220
  • Are you assigning all the points to `c` only in the for loop? `c = [Point(i[0], i[1])]` – AKS Apr 21 '16 at 08:35
  • @AKS what do you mean by that? I thought I replaced the random number creation in the example i linked with my "real" coordinates. I only left out the buffer... – four-eyes Apr 21 '16 at 08:36
  • What I mean is that when you say _that only gives me one (!) geometry object._ which variable is pointing to that object? – AKS Apr 21 '16 at 08:37
  • @AKS I edited my question. Included the `print output` from `c` and `circles` – four-eyes Apr 21 '16 at 08:39

2 Answers2

6

You are overwriting your variable in each iteration of the loop. You need to make c a list and then append to it:

from shapely.geometry import Point
c = []
for i in myCoordinates:
    c.append([Point(i[0], i[1])])

print c

Or you can do it all in one line with a list comprehension:

c = [Point(coord[0], coord[1]) for coord in myCoordinates]
Trev Davies
  • 391
  • 1
  • 10
2

Following would give you three points:

c = [Point(i[0], i[1]) for i in myCoords]

It follows the same list comprehension as the circles:

circles = [Point(random.random(), random.random()).buffer(random.random() * 0.1) for i in range(3)]

What you were doing earlier is assigning the point to a variable c so at the end of the for loop, there is just one point in a list:

for i in myCoordinates:
    c = [Point(i[0], i[1])] # here c is overwritten in each iteration
AKS
  • 18,983
  • 3
  • 43
  • 54