Checking for most recent value on multiple columns in a dataframe

Viewed 52

I am trying to use the following dataframe to recreate a dataset with only one line per country where I fetch the most recent value available for each column. If 2019 has available data, I keep it, if not I move on to 2018 and so on. Being new to Python and coding in general, I have tried to find a starting point for this but I am struggling as no solution I found up to now seems to work.

                 Population totale      PIB en $  Superficie
country     year
Aruba       2019           106314.0           NaN         NaN
            2018           105845.0           NaN       180.0
            2017           105366.0  2.805918e+09       180.0
            2016           104872.0  2.750900e+09       180.0
            2015           104341.0  2.694320e+09       180.0
Afghanistan 2019         38041754.0  2.173959e+10         NaN
            2018         37172386.0  2.112666e+10    652860.0
            2017         36296400.0  2.074494e+10    652860.0
            2016         35383128.0  2.020638e+10    652860.0
            2015         34413603.0  1.975974e+10    652860.0
Angola      2019         31825295.0  9.876968e+10         NaN
            2018         30809762.0  9.963591e+10   1246700.0

emphasized text

Hers is part of the code, I have taken out some functions to make it easier to read, I hope this doesn't stop people from understanding it.

import pandas_datareader.wb as pdr  
import pandas as pd

get_wb_countries = pdr.get_countries()              
wb_countries = list(get_wb_countries['iso2c'])
#wbank_ind defined as series of codes from wb

df_wb = wb.download(indicator=wbank_ind,country=wb_countries,start=2015,end=2020)

# This is what I tried up to now to fetch most recent value :

sorted = df_wb.sort_values(by='year')
result = sorted.drop_duplicates('country', keep='last')

# I get an error message KeyError: Index(['country'], dtype='object')

Thanks for the help. Let me know if you need more information

0 Answers
Related