我有一个熊猫数据框,它是这个简化版的更复杂版本:
# Test data frame
data = {'Geojson': ['{"geometry": {"coordinates": [[[24.950899, 60.169158], [24.953492, 60.169158],[24.953510, 60.170104],[24.950958, 60.169990]]],"type": "Polygon"},"id": 1,"properties": {"GlobalID": "84756blabla","NAME": "Helsinki Senate Square","OBJECTID": 1,"OBS_CREATEDATE": 1641916981000,"OBS_UPDATEDATE": null, "Area_m2": 6861.47},"type": "Feature"}'],'Name': ["Helsinki Senate Square"], 'Type': ["Polygon"]}
df = pd.DataFrame(data)
df.head()
...
Geojson Name Type
0 {"geometry": {"coordinates": [[[24.950899, 60.... Helsinki Senate Square Polygon
如您所见,第一列中嵌入了一个 GeoJSON 文件。我想做的是从该列中提取 GeoJSON 值并将其单独保存为 GeoJSON 文件,但我在执行此操作时遇到了麻烦。在网上寻找帮助并不容易,因为大多数都显示了如何提取 JSON 的示例,它具有与 GeoJSON 不同的属性。
如果可能的话,我还想在同一个 python 脚本中将 GeoJSON 提取为 geopandas GeoDataFrame。
您可能已经猜到,最终目标是能够映射数据或在 GIS 环境中使用它。由于列中有许多 GeoJSON(不只是我的示例中的一个)。该解决方案可能需要迭代。数据类型是多边形,但我也对可以考虑不同要素类型的解决方案感兴趣,例如。点,多线,多边形等...
欢迎任何建议/解决方案。
GeoJSON 是一种 json 格式。我会解析每个功能并将其添加到 FeatureCollection。
这是一个使用你的测试数据的例子:
import json
# list of features: just the one feature in question here
test_features = ['{"geometry": {"coordinates": [[[24.950899, 60.169158], [24.953492, 60.169158],[24.953510, 60.170104],[24.950958, 60.169990]]],"type": "Polygon"},"id": 1,"properties": {"GlobalID": "84756blabla","NAME": "Helsinki Senate Square","OBJECTID": 1,"OBS_CREATEDATE": 1641916981000,"OBS_UPDATEDATE": null, "Area_m2": 6861.47},"type": "Feature"}']
new_feature_collection = {
'type': 'FeatureCollection',
'features': []
}
for feature in test_features:
feature = json.loads(feature)
new_feature_collection['features'].append(feature)
# convert to GeoJSON-formatted string
geojson_out = json.dumps(new_feature_collection, indent=4)
# show it
print(geojson_out)
输出:
{
"type": "FeatureCollection",
"features": [
{
"geometry": {
"coordinates": [
[
[
24.950899,
60.169158
],
[
24.953492,
60.169158
],
[
24.95351,
60.170104
],
[
24.950958,
60.16999
]
]
],
"type": "Polygon"
},
"id": 1,
"properties": {
"GlobalID": "84756blabla",
"NAME": "Helsinki Senate Square",
"OBJECTID": 1,
"OBS_CREATEDATE": 1641916981000,
"OBS_UPDATEDATE": null,
"Area_m2": 6861.47
},
"type": "Feature"
}
]
}