Reputation: 21
I'm having issues writing a GeoPandas DataFrame to a shapefile using the GeoDataFrame.to_file() function. When I run the code below, sometimes I get an empty shapefile, and sometimes it runs but returns nothing at all.
import arcpy
import pandas as pd
import glob
import geopandas as gpd
from shapely.geometry import Point
arcpy.env.overwriteOutput = True
arcpy.env.workspace = r'F:\\GY539_Programming\\project_data'
ws = arcpy.env.workspace
files = glob.glob(ws + '/*.csv')
for filename in files:
df = pd.read_csv(filename, sep=',')
geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])]
gdf = gpd.GeoDataFrame(df, crs='EPSG:4326', geometry=geometry)
gdf.to_file('file.shp', driver='ESRI Shapefile')
Any advice? My data comes from a csv file that contains one column with longitude coordinates and another with latitude coordinates. Here is a snippet of it:
Api Permit ... Latitude Longitude
0 5.000000e+13 163019 ... 61.14 -149.98
1 5.000000e+13 100001 ... 61.21 -149.77
2 5.000000e+13 163015 ... 61.33 -149.91
3 5.000000e+13 165037 ... 61.30 -149.99
4 5.000000e+13 100002 ... 61.42 -149.81
Thanks so much!
Upvotes: 1
Views: 14452
Reputation: 681
Thanks for adding the sample file. The thing is that if you provide a relative filepath like here
gdf.to_file('file.shp', driver='ESRI Shapefile')
then the file is saved in your current working directory which is maybe not the one where you want the file to appear and therefore do not search there whether the file exists. If you want to save the shapefile to another working directory then just supply an absolute filepath like in this example:
filepath = "C:/users/your/file/path"
gdf.to_file(f"{filepath}/file.shp", driver='ESRI Shapefile')
This worked for me with your sample data. I could also verify this by loading the file again as a GeoDataFrame like this:
gpd_df = gpd.read_file(f"{filepath}/file.shp")
Hope that solves it for you as well.
Upvotes: 4