1

I have a multipolygon shapefile representing different cities. I am trying to loop the "v.extract" GRASS command through the different polygons via the Python interface. This is the code I am using:

    for index, row in df.iterrows():
        city_code = (row['city_ID'])
        grass.run_command('v.extract', overwrite=True, input='six_cities', output= 'out' + city_code,
                      where= 'city_ID' + "=" + city_code)

Where df is the df version of the attribute table. However, I always get the module error. I believe this is due to the "where" condition, as I tried to do it without the loop and it works (code below):

grass.run_command('v.extract', overwrite=True, input='six_cities', output= 'out' + city_code,
                      where= " 'city_ID' = 'CH_CH6421' ")

It seems that in order to run, the "where" condition needs to be within quotes. However, I cannot run the loop within quotes, because in this way python recognizes the city_code keyword needed for the loop as a string.

1 Answer 1

1

If you prepare your where clause first, it should work (I use f-strings below):

Edited Sorry for the mistake. If you enclose the where clause in double quotes, it should work. (tested here, this time).

  for index, row in df.iterrows():
        city_code = (row['city_ID'])
        expr = f'"city_ID={city_code}"'
        out = f"out_{city_code}"
        grass.run_command('v.extract', overwrite=True, input='six_cities', output=out, where=expr)

Give this a try, and post back.

3
  • Unfortunately it still doesn't work.. I always get this error message: "Module run None v.extract --o input=six_cities output=out_CH_CH6421 where=city_ID=CH_CH6421 ended with error". I definitely cannot understand where the problem is..
    – okapina
    Commented Jan 20, 2023 at 13:53
  • 1
    I missed the double quotes around the where clause. See edited answer.
    – Micha
    Commented Jan 22, 2023 at 9:01
  • I tried with the entire clause within double quotes but it didn't work for me, however, putting only {city code} within double quotes did the trick! Thank you Micha your suggestion helped to reach the solution :-) Here below the full working code: ´´´ for index, row in df.iterrows(): city_code = (row['city_ID']) expr = f'ciry_ID= "{city_code}"' out =f"out_{city_code}" grass.run_command('v.extract', overwrite=True, input='six_cities', output=out, where=expr) ´´´
    – okapina
    Commented Jan 23, 2023 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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