1

I have the following dataframe

id  x1              y1              x2              y2
0   431634.751688   4.581910e+06    431692.792776   4.581814e+06
1   431930.133825   4.581873e+06    431938.831274   4.581865e+06
2   431926.171004   4.581867e+06    431930.133825   4.581873e+06
3   431930.133825   4.581873e+06    431936.892345   4.581880e+06    

The values (x1, y1) are the starting point coordinates, and (x2, y2) belong to the ending point.

How can I turn the single coordinates into linestrings?

1
  • You need to describe how those coordinates should form (a) inestring(a). What is their order. Which ones belong together. Commented Sep 27, 2019 at 14:33

1 Answer 1

2

Assuming you want a linestring for each row, you can do the following:

In [1]: from shapely.geometry import LineString 

In [2]: df = pd.DataFrame(np.random.randn(2,4), columns=['x1', 'y1', 'x2', 'y2'])

In [3]: df
Out[3]: 
         x1        y1        x2        y2
0  0.866753  0.508888 -1.909955 -0.669491
1  0.190494 -0.985312 -0.680165 -1.126238

In [4]: df.apply(lambda row: LineString([(row.x1, row.y2), (row.x2, row.y2)]), axis=1)
Out[4]: 
0    LINESTRING (0.8667529205642079 -0.669490509579...
1    LINESTRING (0.1904941313773766 -1.126237639460...
dtype: object

Your Answer

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

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