1

I have produced a GeoPandas geodataframe (attached) with rows containing "loss_year" between 2001 and 2021, and some area values (pictured).

enter image description here

I wish to append the omitted years between 2001 - 2021 to the gdf, assigning 0 values to the geometry, area_ha and area_perc collumns. I will drop the geometry column before writing to a CSV.

Here is some pseudocode:

"""
for yr in 2000 - 2021:
    if yr not in gdf.loss_year:
          results.append({'loss_year'[yr], 'area_ha': 0.00, 'area_perc' : 0})
"""   

1 Answer 1

1

See: Missing data, insert rows in Pandas and fill with NAN

import geopandas as gpd
import pandas as pd
df = pd.DataFrame(gpd.read_file(r'C:\GIS\data\testdata\years.shp'))

#My dataframe have 3 rows/years: 2001, 2005, 2021:
#   loss_year   area  prc                                           geometry
#0       2001  42524    1  POLYGON ((14.71964 58.73581, 14.71703 59.05656...
#1       2005      1    1  POLYGON ((15.28429 58.93355, 15.28690 59.24807...
#2       2021    111    1  POLYGON ((14.62025 58.23570, 14.61672 58.56270...

df = df.set_index("loss_year").reindex(pd.Index(range(2001,2022,1), name="loss_year")).reset_index()
df = df[['loss_year','area','prc']].fillna(0)

#Now all the years from 2001-2021 are there:
# print(df.head(3))
#    loss_year     area  prc
# 0       2001  42524.0  1.0
# 1       2002      0.0  0.0
# 2       2003      0.0  0.0
# print(df.tail(3))
# 18       2019    0.0  0.0
# 19       2020    0.0  0.0
# 20       2021  111.0  1.0

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.