Applying geometric operation on multiple GeoDataFrames
Use a dict
shps = ['test1.shp','test2.shp','test3.shp']
dfs = {}
for shp in shps:
df = gpd.read_file(shp)
dissolved_df = df.dissolve(...)
dfs[shp] = df
dfs[shp+'_dissolved'] = df_dissolved
Or
dfs = {}
dfs_dissolved = {}
for shp in shps:
df = gpd.read_file(shp)
dissolved_df = df.dissolve(...)
dfs[shp] = df
dfs_dissolved[shp] = df_dissolved
You need to get variable names. So you can use python exec
method to create variable names using string
. So that you can get variable names in a for
loop.
I assume your file names are test1.shp, test2.shp, ..., test20.shp
.
Try this script:
import geopandas as gpd
prefix = "shp_"
suffix = "_dissolved"
dissolve_by = "field_name" # CHANGE HERE
file_count = 20
# read shapefiles as GeoDataframes and assign it to shp_?
for i in range(1, file_count+1):
# command is string here
command = prefix + str(i) + ' = gpd.read_file("test' + str(i) + '.shp")'
print ("Running: " + command)
exec(command)
# Now, you can use shp_1 as variable
# print(shp_1)
# dissolve GeoDataFrames and assign it to shp_?_dissolved
for i in range(1, file_count+1):
command=prefix + str(i) + suffix + ' = ' + prefix + str(i) + '.dissolve(by="' + dissolve_by + '")'
print("Running: " + command)
exec(command)
print("Done")
# Now, you can use shp_1_dissolved as variable
# print(shp_1_dissolved)
I must confess that this is not an appropriate way. But it'd be better use exec
method to create a variable whose name depends on another variable name.