【问题标题】:How to convert multi-index DataFrames to GeoJSON FeatureCollections如何将多索引 DataFrames 转换为 GeoJSON FeatureCollections
【发布时间】:2016-05-30 23:45:54
【问题描述】:

我有两个multi-indexDataFrames如下。

  • 第一个DataFrame

  • 第二个DataFrame

我想用上面的DataFrames为每个对象构造如下格式的GeoJSONFeatureCollections,然后插入到MongoDB中。

# GeoJSON
# Loop over all Object IDs

object[i] = {
    "type": "FeatureCollection",
    "features": [
        {
            # 1st DataFrame
            "type": "Feature",
            "properties": {},
            "geometry": {"type": "Polygon", "coordinates": [[[·,·],[·,·],[·,·],...]]}
        },
        {
            # 2nd DataFrame
            "type": "Feature",
            "properties": {},
            "geometry": {"type": "LineString", "coordinates": [[·,·],[·,·],[·,·],...]}
        }
    ]
}

# MongoDB
# Loop over all Object IDs

from pymongo import MongoClient
client = MongoClient()
db = client.object
result = db.object.insert_one(object[i])

由于特定对象的点数随机,而特征PolygonLingString中的点数相同的FeatureCollection 彼此不一定相等,很难使用for 循环来实现该目标。任何人都可以对这个问题提出一个想法吗?

【问题讨论】:

    标签: python mongodb dataframe geojson multi-index


    【解决方案1】:

    如果“点数”表示“每个特征中的点数”,那么这应该有效:

    # transform to hierarchical series of [lat, lon]
    s1 = df1.apply(lambda row: pd.concat([row['lat'], row['lon']]).tolist())
    # now group that series by object id into a series of lists
    coords1 = s1.groupby(level=0).apply(lambda s : s.tolist())
    

    df2 -> s2 也是如此。这会产生[[lat_0, lon_0], [lat_1, lon_1], ...],它是一个 LineString。 要使 df1 -> s1 成为 geojson 多边形的坐标列表/数组,您需要将每个坐标成员列表包装在另一个列表中。有关多边形坐标的规则,请参阅RFC 7946 section 3.1.6。最后,您必须将所有这些都包装在 FeatureCollection 中的特征中的多边形/几何中。如果这看起来需要大量写作,请考虑导入 json 库的 geojson 扩展。

    我在gist 中构建了一个更通用的函数来将 pandas 聚合到几何图形。

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 2021-11-30
      • 2018-03-16
      • 2019-03-06
      • 1970-01-01
      • 2021-12-17
      • 2021-08-28
      • 2022-12-19
      • 1970-01-01
      相关资源
      最近更新 更多