<jupyter_start><jupyter_text>World Databank GDP per Capita In this document we are going to explore the data of GDP per capita. For doing that we will use the package `wbdata`. We are going to display the data as time series as well as in a map.<jupyter_code>import wbdata
import datetime 
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [15,10]<jupyter_output><empty_output><jupyter_text>First, let's see the GDP per capita of the world from 1990 to 2020.<jupyter_code>start_year=1990
end_year=2021
countries = ["WLD"]
indicator = {"NY.GDP.PCAP.PP.KD": "gdppc"} 
data_date = datetime.datetime(start_year, 1, 1), datetime.datetime(end_year, 1, 1) 

#get info
wbdata_info = wbdata.get_dataframe(indicator, country=countries, convert_date=True, data_date=data_date)
wbdata_info=wbdata_info.reset_index()

#plot data
plt.plot(wbdata_info['date'], wbdata_info["gdppc"] , linewidth=4)
plt.legend(countries)
plt.show()<jupyter_output><empty_output><jupyter_text>MetadataBefore continuing, we will explain two aspects of `wbdata`.* Country Information* Indicators   Country Information<jupyter_code>countries_info=pd.DataFrame(wbdata.get_country())
region_name=countries_info['region'].apply(lambda x: x['value'])
countries_info['region_name']=region_name
countries_info.head()
#Show country info
print("Columns: ")
print(countries_info.columns.tolist())
print("\n ")
#Show regions
print("Regions: ")
print(set(region_name.tolist()))
print("\n ")
#Show income levels
print("Income levels: ")
pd.DataFrame(wbdata.get_incomelevel() )<jupyter_output>Columns: 
['id', 'iso2Code', 'name', 'region', 'adminregion', 'incomeLevel', 'lendingType', 'capitalCity', 'longitude', 'latitude', 'region_name']

 
Regions: 
{'Aggregates', 'North America', 'East Asia & Pacific', 'Latin America & Caribbean ', 'Europe & Central Asia', 'South Asia', 'Middle East & North Africa', 'Sub-Saharan Africa '}

 
Income levels:<jupyter_text>IndicatorsThe other aspect is the different indicators. The indicators are grouped by their source of data.For example, let's list the different source of data.<jupyter_code>wbsource=pd.DataFrame(wbdata.get_source() )
wbsource.head()<jupyter_output><empty_output><jupyter_text>From the source "Doing Business" (with id=1) we can obtain several indicators:<jupyter_code>indicators=pd.DataFrame(wbdata.get_indicator(source=1) )
indicators.head()<jupyter_output><empty_output><jupyter_text>Alternatively we can search the indicators by using the `search_indicators` function. For example, we can search for indicators that measure the "unemployment".<jupyter_code>indicator=pd.DataFrame(wbdata.search_indicators("unemployment") )
indicator.head()<jupyter_output><empty_output><jupyter_text>In this document we are going to use the indicator of GDP per capita "NY.GDP.PCAP.PP.KD". We can see more information by using the `get_indicator` function.<jupyter_code>gdppc=pd.DataFrame(wbdata.get_indicator("NY.GDP.PCAP.PP.KD") )
print(gdppc.loc[0]["name"])
gdppc.head()<jupyter_output>GDP per capita, PPP (constant 2017 international $)<jupyter_text>Time seriesOn the first analysis we are going to see the evolution of the GDP per capita of some countries. First we build a function to plot the time series<jupyter_code>def plot_indicator_time(indicator,countries,start_year,end_year):
    data_date = datetime.datetime(start_year, 1, 1), datetime.datetime(end_year, 1, 1)
    indicator_name=list(indicator.values())[0]
    #Get info
    wbdata_info = wbdata.get_dataframe(indicator, country=countries, convert_date=True, data_date=data_date)
    #Transform data to have a country in each column
    if len(countries)==1:
        wbdata_info["country"]=countries[0]
    wbdata_info_countr=wbdata_info.reset_index()
    wbdata_info_countr=wbdata_info_countr.pivot(index='date', columns='country', values=indicator_name)
    wbdata_info_countr=wbdata_info_countr.reset_index()
    #Plot!
    country_names=list(set(wbdata_info_countr.columns) - set(["country" ,"date"]) )
    plt.plot(wbdata_info_countr['date'], wbdata_info_countr[country_names] , linewidth=5)
    plt.legend(country_names)
    plt.show()<jupyter_output><empty_output><jupyter_text>We then provide the indicator, countries and time range to plot<jupyter_code>start_year=2000
end_year=2021
indicator = {"NY.GDP.PCAP.PP.KD": "gdppc"} 
data_date = datetime.datetime(start_year, 1, 1), datetime.datetime(end_year, 1, 1) 

countries = ["ESP","FRA","IRL","SGP"]
plot_indicator_time(indicator,countries,start_year,end_year)<jupyter_output><empty_output><jupyter_text>MapsThe second analysis will deal with the map. The countries on the map will be color-coded according to their GDP per capita.<jupyter_code>import geopandas as gpd
import numpy as np; 
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>Create a function to plot the map:<jupyter_code>#This has as input a dictionary (id_value_dict) maping the value of the indicator to the country codes
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) 

def plot_map(id_value_dict):
    gdf["indicator"]=gdf["iso_a3"].apply(lambda x: id_value_dict.get(x,float('nan')) )
    fig, ax = plt.subplots()
    gdf.plot(column='indicator', cmap='summer',scheme="natural_breaks", legend=True, ax=ax , missing_kwds={'color': 'lightgrey'})
    plt.show()<jupyter_output><empty_output><jupyter_text>Note: The variable `gdf` contains the code, name and polygon of the countries. However some countries do not have the proper code "iso_a3" (`gdf[gdf["iso_a3"]=="-99"]`) so we make a small fix.<jupyter_code>gdf.at[gdf[gdf["name"]=="France"].index,'iso_a3']='FRA'
gdf.at[gdf[gdf["name"]=="Norway"].index,'iso_a3']='NOR'<jupyter_output><empty_output><jupyter_text>Then, obtain the data and transform and map the values to their country code:<jupyter_code># get info
year=2010
indicator = {"NY.GDP.PCAP.PP.KD": "gdppc"}

indicator_name=list(indicator.values())[0]
data_date = datetime.datetime(year, 1, 1), datetime.datetime(year, 1, 1) 
wbdata_info = wbdata.get_dataframe(indicator, convert_date=True, data_date=data_date).reset_index()

#Map the values of the indicator to the country code
countries_info=pd.DataFrame(wbdata.get_country())
country_id_name=dict(zip(countries_info["name"], countries_info["id"])) #get a dictionary country  - code
wbdata_info["id"]=wbdata_info["country"].apply(lambda x: country_id_name.get(x,"NA") )
country_indicator_dict=dict(zip(wbdata_info["id"], wbdata_info[indicator_name])) #get a dictionary code  - value<jupyter_output><empty_output><jupyter_text>After that, we can plot the information in a map:<jupyter_code>plot_map(country_indicator_dict)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12514952153110048, 'fraction_numerical': 0.010316985645933014, 'mean_word_length': 7.575641025641025, 'pattern_counts': {'":': 3, '<': 55, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '536249', 'license': 'MIT', 'n_tokens_mistral': 2405, 'n_tokens_neox': 2288, 'n_words': 523, 'path': 'worldbankdata/worldbankdata.ipynb', 'repo_name': 'alberto-poncelas/data_exploration_notebooks', 'size': '6688'}