简体   繁体   English

如何在 Python 中将 GeoDataFrame 保存到磁盘?

[英]How can I save a GeoDataFrame to disk in Python?

I have an GeoDataFrame called merged and I'm having a very hard time saving it to disk.我有一个名为已merged的 GeoDataFrame,我很难将它保存到磁盘。
merged is obtained through this loop:通过此循环获得merged

import pandas as pd
import geopandas as gpd
import osmnx as ox

city=gpd.read_file('C:/folder/city.json')
circ=[]

for i in (0, 1):
    graph = ox.graph_from_polygon(city.geometry[i])
    stat = ox.basic_stats(graph)
    circ.append(stat['circuity_avg'])

circ=pd.Series(circ)
merged=pd.concat([city, circ], axis=1)

I simply want to save merged to a file, as a json file or another format that preserves the geometry, so that I can then use the data in R. Here are the methods I've tried:我只是想将merged后的文件保存为 json 文件或另一种保留几何形状的格式,以便我可以在 R 中使用数据。以下是我尝试过的方法:

1. 1.

merged.to_file('merged.json', driver='GeoJSON')

which gives这使

Attribute Error 'int' object has no attribute 'encode'属性错误'int' 对象没有属性 'encode'

Does anyone know why merged is classed as 'int' while it is a GeoDataFrame (that's what's indicated when I do type(merged) )?有谁知道为什么merged被归类为“诠释”,而这是一个GeoDataFrame(这是什么表示的,当我做type(merged) )?

2. 2.

with open('x.geojson', 'w') as f:
        f.write(merged_short.to_json())

This creates a x.geojson file in my Jupyter Lab environment but it doesn't save it to disk.这会在我的 Jupyter Lab 环境中创建一个x.geojson文件,但不会将其保存到磁盘。 That's understandable since I don't specify a path to save to.这是可以理解的,因为我没有指定要保存到的路径。 However, I on't know how to add a path.但是,我不知道如何添加路径。

3. 3.

merged.to_csv("C:/folder/merged.cs")

This works but, since the data is saved as csv, the geometry is not preserved.这有效,但由于数据保存为 csv,因此不保留几何。

4. 4.

merged.to_json("C:/folder/merged.cs")

But that gives ValueError: Unknown na method .但这给出了ValueError: Unknown na method

I'm very surprised I haven't found a simple way to save GeoDataFrames to a file on my computer.我很惊讶我还没有找到一种简单的方法来将 GeoDataFrames 保存到我的计算机上的文件中。 Is there a simple method to save GeoDataFrames?有没有一种简单的方法来保存 GeoDataFrames?

Solution解决方案

with open('C:/folder/merged.json', 'w') as f:
        f.write(merged_short.to_json())

Meaning I just needed to specify the full path.这意味着我只需要指定完整路径。

Your version 2 will save a file, but to a relative location.您的版本 2 将保存一个文件,但保存到一个相对位置。 Try providing an absolute path:尝试提供绝对路径:

with open('C:/folder/x.geojson', 'w') as f:
    f.write(merged_short.to_json())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM