TransWikia.com

Geopandas Points within Polygon; Is there a method to convert bool series result into a python list?

Geographic Information Systems Asked on July 20, 2021

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

One Answer

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 ]

Correct answer by Kadir Şahbaz on July 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP