0

To do some geospatial analysis I am using the USA counties map from topojson/us-atlas repository

After loading the link https://cdn.jsdelivr.net/npm/us-atlas@3/counties-10m.json in geopandas I get the geodataframe correctly.

import geopandas as gpd
counties = gpd.read_file('https://cdn.jsdelivr.net/npm/us-atlas@3/counties-10m.json')

Then I just do the following to get the longitude and latitude -

counties['lon'] = counties['geometry'].centroid.x
counties['lat'] = counties['geometry'].centroid.y

But I get the error -

IndexError: list index out of range

Only the centroid attribute seems to give the output :
counties['geometry'].centroid gives -

0       POINT (-113.75823 35.70499)
1        POINT (-90.40498 30.62627)
2       POINT (-114.13825 43.00235)
3        POINT (-96.40159 47.77421)
4        POINT (-97.24835 46.93312)

Any idea how to get the longitude and latitude of the counties / states from the us-atlas file?

6
  • Is it possible that you have missing geometry somewhere? Or invalid? That could cause the error. Oct 28, 2020 at 9:15
  • @martinfleis Ummm....but if i had missing geometry then calling just centroid too would have given error right? I plotted the raw data and it worked, so I figured that atleast the geometries are alright. But I not so sure. Maybe you can check since the file is there in topojson's repository.
    – jar
    Oct 28, 2020 at 9:23
  • No, centroid gives None in that case. You can check with counties.geometry.isna().any(), counties.geometry.is_empty().any() and counties.geometry.is_valid().any(). Oct 28, 2020 at 9:27
  • I see. When I tried counties.geometry.isna().any() I get False. But the rest give the same error TypeError: 'Series' object is not callable
    – jar
    Oct 28, 2020 at 9:44
  • Of sorry, those are properties, so without (). As counties.geometry.is_empty.any() Oct 28, 2020 at 10:12

1 Answer 1

2

You get IndexError of this kind if the GeoSeries with centroid does contain empty geometry.

You have to check if all geometries are valid and non-empty.

counties.geometry.is_empty.any()

counties.geometry.is_valid.any()

If you get True for any of those, you will have to drop affected rows. On of the options is below.

empty = counties.geometry.is_empty

counties_non_empty = counties[~empty]

counties_non_empty['lon'] = counties_non_empty['geometry'].centroid.x
counties_non_empty['lat'] = counties_non_empty['geometry'].centroid.y

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.