如何编写Python循环以将大量坐标转换为GeoJSON LineString格式?

时间:2016-02-19 21:38:29

标签: python loops geojson coordinate

我使用pandasDataFrame multi-index中重建了我的数据集,现在采用以下格式。

In [1]: df.head(12)
Out [1]:

enter image description here

为了将其置于GeoJSON LineString格式并在地图上显示,我需要在每个点和每一行上写Python loop数以百万计的卫星观测点。作为参考,以下示例指定了GeoJSON LineString

{ type: "LineString", coordinates: [ [ 40, 5 ], [ 41, 6 ] ] }

但是,并不总是如图所示,前三行包含4个点,此数据集中特定行的点数是完全随机的,范围从4到数百。

我很困惑如何编写一个Python loop,可以帮助我使用GeoJSON将我的坐标设置为LineString multi-index类型,例如

In [2]: df.Longitude[1][4]
Out [2]: 128

谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

groupbyto_json的组合似乎效果很好。

import pandas as pd
import numpy as np
import pprint

arrays = [np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4]),
          np.array([1, 2, 3, 1, 2, 1, 2, 3, 4, 5, 1, 2])]

df = pd.DataFrame(np.arange(24).reshape(12,2), 
                  index=arrays, columns=['Longitude', 'Lattitude'])

dd = {"type":"Feature", 
      "geometry":{"type":"Linestring",
                  "coordinates":None
                 },
      "properties":{"prop0":'red',
                    "prop1":'dashed'
                   }
     }

for _, group in df.groupby(level=0):
    dd["geometry"]["coordinates"] = group.to_json(orient='values')
    pprint.pprint(dd)

输出:

{'geometry': {'coordinates': '[[0,1],[2,3],[4,5]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}
{'geometry': {'coordinates': '[[6,7],[8,9]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}
{'geometry': {'coordinates': '[[10,11],[12,13],[14,15],[16,17],[18,19]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}
{'geometry': {'coordinates': '[[20,21],[22,23]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}