12

How can I convert a shapely point geometry like following to numpy array?

[<shapely.geometry.point.Point object at 0x000001CEF6978DA0>, <shapely.geometry.point.Point object at 0x000001CEF6978CF8>, <shapely.geometry.point.Point object at 0x000001CEF6978E10>]

or in str:

['POINT (656822.0796426814 -185003.7243437266)', 'POINT (656917.7545657885 -184985.6672704536)', 'POINT (656997.7888963958 -185001.578684116)'] 

to a numpy array with shape (3,2)like this:

[[ 656822.0796426814 -185003.7243437266]
[ 656917.7545657885 -184985.6672704536]
[ 656997.7888963958 -185001.578684116]]
2
  • 1
    What have you already tried, where are you stuck?
    – Dirk
    Commented Aug 21, 2017 at 20:50
  • Not clear why this is marked as off-topic, has certainly seen a lot of visitors! At most one could possibly argue this is better housed in SO, but seems it could equally be here. Could a moderator-level user clarify?
    – jmetz
    Commented Apr 10, 2023 at 14:19

2 Answers 2

6

I created a shapefile with your point coordinates and the following code produces those numpy arrays:

import fiona
from shapely.geometry import shape
import numpy as np

path = '/home/zeito/pyqgis_data/points_list.shp' #your points

points = fiona.open(path)

geoms = [ shape(feat["geometry"]) for feat in points ]

list_arrays = [ np.array((geom.xy[0][0], geom.xy[1][0])) for geom in geoms ]

for array in list_arrays:
    print array

Result after running it is:

[ 656822.07964268 -185003.72434373]
[ 656917.75456579 -184985.66727045]
[ 656997.7888964  -185001.57868412]
2
  • Just for completion: if you want to have the coordinates in one big array, you have to define an empty one with arr=np.empty((0,2)) and then append it in the for loop with arr = np.append(arr,np.array([array]),axis=0)
    – Leo
    Commented Apr 10, 2019 at 7:12
  • I think it is cleaner to do the following - list_arrays = list(zip(*ls.xy)) Then there is no ambiguity with indexes and it is easier to read. Or if you need it to be a list of list, list(map(list, zip(*ls.xy)))
    – Nick Brady
    Commented Oct 22, 2021 at 14:42
2

Create a list of the coordinates and convert into a numpy array using np.array().

import numpy as np
from shapely.geometry import Point
mypoints = [Point(1, 2), Point(1.123, 2.234), Point(2.234, 4.32432)]

listarray = []
for pp in mypoints:
    listarray.append([pp.x, pp.y])
nparray = np.array(listarray)

print mypoints
print nparray

Printed output:

[<shapely.geometry.point.Point object at 0x10f1bd350>, <shapely.geometry.point.Point object at 0x10f1bd410>, <shapely.geometry.point.Point object at 0x10f1bd3d0>]
[[ 1.       2.     ]
 [ 1.123    2.234  ]
 [ 2.234    4.32432]]

Not the answer you're looking for? Browse other questions tagged or ask your own question.