4

I have a collection of geodataframes in my Python environment. How can I apply for each GeoDataFrame the same spatial operation using following manner and create a new variable with the reference that it was manipulated by attaching "_dissolved"?

shp_1 = gpd.read_file('test1.shp')
shp_2 = gpd.read_file('test2.shp')
shp_3 = gpd.read_file('test3.shp')

lst = [shp_1,shp_2,shp_3]

for i in lst:
    
    i = i.dissolve(...)

Expected result would be the variables:

shp_1_dissolved
shp_2_dissolved
shp_3_dissolved

I tried something like:

i'_dissolved' = i.dissolve(...)

or

i + '_dissolved' = i.dissolve(...)
1
  • Up to 20 normally
    – DrSnuggles
    Sep 7 '20 at 12:24
6

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
5

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.