๐Ÿ” Extract Field Names Containing 'type' (Integer Fields Without Domain) from GDB Using ArcPy

  ⚙️ How the Script Works ๐Ÿ—‚️ Geodatabase Setup The script starts by pointing to a target File Geodatabase (.gdb) and initializing a CSV ...

Saturday, April 19, 2025

Post #2: Reading and Writing Shapefiles using GeoPandas

 

Title: How to Read and Write Shapefiles with GeoPandas (Python GIS Tutorial)


๐Ÿ“Introduction

In GIS, shapefiles are one of the most common formats you'll work with. With Python and GeoPandas, you can read, edit, and write shapefiles with just a few lines of code. It’s a powerful way to automate tasks and reduce your dependency on desktop tools.

Let’s look at how to load shapefiles, view their structure, filter features, and save new versions.


๐Ÿ“‚ Step 1: Read a Shapefile

python
import geopandas as gpd # Load shapefile roads = gpd.read_file("data/roads.shp") # Preview the data print(roads.head())

๐Ÿง  What’s Inside a GeoDataFrame?

You can check out the column names and geometry type like this:

python
print(roads.columns) print(roads.geom_type.unique()) print(roads.crs) # Coordinate reference system

๐Ÿ” Step 2: Filter Features

Let’s say we only want to keep major roads:

python
major_roads = roads[roads["road_type"] == "Major"] print(f"Total major roads: {len(major_roads)}")

๐Ÿ“ˆ Optional: Plot the Filtered Data

python
import matplotlib.pyplot as plt major_roads.plot(color="red") plt.title("Major Roads Only") plt.show()

๐Ÿ’พ Step 3: Write a New Shapefile

Save the filtered features to a new shapefile:

python
major_roads.to_file("output/major_roads.shp")

Or export it as GeoJSON:

python
major_roads.to_file("output/major_roads.geojson", driver="GeoJSON")

๐Ÿ” Bonus: Reproject the Data

Need your data in WGS84 (EPSG:4326)? Use:

python
roads_4326 = roads.to_crs("EPSG:4326") roads_4326.to_file("output/roads_wgs84.shp")

๐Ÿงน Tips for Working with Shapefiles

  • Always keep all .shp, .shx, .dbf, .prj files together.

  • For non-English column names or long field names, consider simplifying them before exporting.

  • Use .to_crs() before exporting if your tools expect a specific projection (e.g., WGS84 for web maps).


๐ŸŽฏ Conclusion

In just a few lines of Python, you can read, filter, and save shapefiles—perfect for automating spatial workflows or cleaning data before analysis.


๐Ÿ“Œ Next Up:

➡️ Spatial Joins and Attribute Queries in Python GIS

No comments:

Post a Comment