Create Shapefile from Data Frame¶
This example demonstrates how to create a shapefile (.shp and other required files) from a Pandas dataframe. To do this, you must first create a column containing the geometries and call it 'geom'. You can also add more columns, each containing additional information about the geometry in the 'geom' column. In this example, points are used as geometries; however, the next subsection introduces other types of geometry and explains how to create them.
Import Modules and Packages¶
In [1]:
Copied!
import geokit.core.srs
import geokit.core.geom
import geokit.core.vector
import pandas as pd
import numpy as np
import geokit.core.srs
import geokit.core.geom
import geokit.core.vector
import pandas as pd
import numpy as np
Create Points¶
In [2]:
Copied!
# Choose an srs for the geometries
srs = geokit.core.srs.EPSG3035
# Create random point geometries
geoms = []
for i in range(200):
geoms.append(geokit.core.geom.point(np.random.random(2), srs=srs))
# Choose an srs for the geometries
srs = geokit.core.srs.EPSG3035
# Create random point geometries
geoms = []
for i in range(200):
geoms.append(geokit.core.geom.point(np.random.random(2), srs=srs))
Create DataFrame¶
In [3]:
Copied!
# Create a DataFrame with column called "geom" for the geometries
df = pd.DataFrame({"geom": geoms})
# Create a DataFrame with column called "geom" for the geometries
df = pd.DataFrame({"geom": geoms})
Add Additional Columns¶
In [4]:
Copied!
# Add Attributes for each geometry
size = np.random.randint(100, size=len(geoms))
df["size"] = size
color = [["blue", "green", "red", "yellow"][i] for i in np.random.randint(4, size=len(geoms))]
df["color"] = color
# Show the table for clarification
df.head()
# Add Attributes for each geometry
size = np.random.randint(100, size=len(geoms))
df["size"] = size
color = [["blue", "green", "red", "yellow"][i] for i in np.random.randint(4, size=len(geoms))]
df["color"] = color
# Show the table for clarification
df.head()
Out[4]:
| geom | size | color | |
|---|---|---|---|
| 0 | POINT Z (0.435147047703236 0.939267064088742 0) | 95 | red |
| 1 | POINT Z (0.672798892757984 0.960348660016403 0) | 27 | blue |
| 2 | POINT Z (0.791466852382911 0.327802464808511 0) | 71 | yellow |
| 3 | POINT Z (0.210508080750499 0.229797795052859 0) | 18 | red |
| 4 | POINT Z (0.356381475662292 0.61304085084958 0) | 56 | green |
Store the Data Frames as Shapefile¶
Please note that the shapefile consists of the following files: .shp, .prj, .dbf and .shx.
In [5]:
Copied!
# Save as a shapefile
geokit.core.vector.createVector(df, output="outputShapeFile.shp")
# Save as a shapefile
geokit.core.vector.createVector(df, output="outputShapeFile.shp")
Out[5]:
'/home/docs/checkouts/readthedocs.org/user_builds/geokit/checkouts/latest/docs/Examples/_02_vector/outputShapeFile.shp'