1

Working in Linux OS with Visual Studio Code; Jupyter Notebook module.

import geopandas as gpd
ubp1 = "/media/rg/data/map/urban boundary.geojson"
poly1 = gpd.read_file(ubp1)

import shapely.speedups
shapely.speedups.enable()

inUrban = gdf.within(poly1.loc[0, 'geometry'])

I'd like to manipulate the bool result so I have converted the pandas series to a Python list.

s = list(inUrban)

I tried this:

urban = []
dex = 0
for i in s:
    if s[dex] == "True":
        urban[dex] = 2
    else:
        urban[dex] = 0
    dex=+1

but that resulted in error:

IndexError                   Traceback (most recent call last)
<ipython-input-52-ecba01b18d72> in <module>
      8         urban[dex] = 2
      9     else:
---> 10         urban[dex] = 0
     11     dex=+1

IndexError: list assignment index out of range

1 Answer 1

3

The error is raised when you try to assign a value to an index position which doesn't exist in urban list.

You can use append() to solve this error.

urban = []
dex = 0
for i in s:
    if s[dex] == "True":
        urban.append(2)
    else:
        urban.append(0)
    dex=+1

A better way to solve this error would be to use the following:

urban = [ 2 if v == "True" else 0 for v in s ]
1
  • Thank you. Both suggestions worked after I removed the double quotes around True as it is bool type. I like your second suggestion. I will have to learn more about that concept.
    – Bob
    Mar 13, 2021 at 21:21

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.