简体   繁体   中英

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 is obtained through this loop:

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:

1.

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

which gives

Attribute Error 'int' object has no attribute '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) )?

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. That's understandable since I don't specify a path to save to. However, I on't know how to add a path.

3.

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

This works but, since the data is saved as csv, the geometry is not preserved.

4.

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

But that gives ValueError: Unknown na method .

I'm very surprised I haven't found a simple way to save GeoDataFrames to a file on my computer. Is there a simple method to save 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. Try providing an absolute path:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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