# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
"""
Import necessary modules
"""
import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns
import pycountry
import plotly.express as px
import plotly.graph_objs as go
"""
# **Exploratory Data Analysis / Data Preprocessing**
> ## **Data Visualization**
***
"""
"""
## **Exploratory Data Analysis / Data Preprocesesing**
"""
"""
**Data Familiarization**
"""
df = pd.read_csv('/kaggle/input/forbes-billionaires-of-2021/Billionaire.csv', index_col='Rank')
df.head()
"""
2755 Billionaires 
"""
df.shape
df.info()
df.describe()
"""
The top industries that produce billionaires 
"""
df['Industry'].value_counts()
"""
**Data Wrangling**
"""
"""
I'm not going to drop the rows that contain NaN because I'd rather have more data on billionaries (missing some ages) than less 
"""
df.isna().sum()
df['NetWorth'] = df['NetWorth'].str.replace('$', '', regex=True)
df['NetWorth'] = df['NetWorth'].str.replace('B', '', regex=True)
df['NetWorth'] = df['NetWorth'].astype(float)
df.head()
"""
From the code below, we now know that the average billionaire is worth ~ $4.75 B 
"""
df.describe()
"""
**DataFrame Creation/Aggregation**
"""
"""
*Technology billionaires*
"""
df_tech = df.loc[df['Industry'] == 'Technology'].copy()
df_tech
"""
*Finance and Investments Billionaires*
"""
df_money = df.loc[df['Industry'] == 'Finance & Investments'].copy()
df_money
"""
*Manufacturing billionaires*
"""
df_man = df.loc[df['Industry'] == 'Manufacturing'].copy()
df_man
"""
### **Data Visualization**
"""
"""
Who are the top 5 billionaires in 2021?
"""
plt.figure(figsize=(10, 6))
plt.barh(df['Name'].head(10), df['NetWorth'].head(10), color='limegreen')
plt.title('The top 10 billionaires in the world as of 2021', weight='bold')
plt.xlabel('NetWorth (in billions)')
plt.ylabel('Billionaires')
plt.show()
"""
What are the countries with the most billionaires?
"""
df['Country'].value_counts()[:5].plot(kind='barh', cmap='Pastel1', figsize=(9,6))
plt.title('The top 5 countries with the most billionaires', weight='bold')
plt.xlabel('Number of Billionaires')
plt.ylabel('Countries')
plt.show()
"""
What industries produce the most billionaires?
"""
df['Industry'].value_counts()[:5].plot(kind='barh', cmap='Pastel2', figsize=(9,6))
plt.title('The top 5 industries that produce billionaires', weight='bold')
plt.xlabel('Number of Billionaires')
plt.ylabel('Industries')
plt.show()
"""
Create df_map - dataframe needed to visualize the world's billionaires
"""
df_map = df.drop_duplicates().groupby('Country').count().copy()

df_map = df_map['Name'].copy()

df_map = df_map.sort_values(ascending=False)

df_map = pd.DataFrame(df_map)

df_map.rename(columns = {'Name':'Billionaires'}, inplace = True)
df_map.head()
"""
Add the iso-alpha 3 digit country codes column and the full Country Name column
"""
for Country in df_map.index:
    code = [value.alpha_3 for value in pycountry.countries if (value.name==Country)] #retrieves iso-alpha codes
    if len(code)==0: #if iso alpha code doesn't match country
        df_map.loc[Country,"Sign"]= None
        df_map.loc[Country,"Country Name"]= Country
    else: #if iso alpha code does match country
        df_map.loc[Country,"Sign"]= code[0]
        df_map.loc[Country,"Country Name"]= Country
"""
NaN values in df_map
"""
df_map[df_map.isna().any(axis=1)]
"""
Manually impute iso-alpha missing values with first 3 letters of country name
"""
filler = pd.DataFrame(index=df_map.index[df_map.isnull().any(axis=1)], data=['RUS', 'TAI', 'SOU', 'VIE', 'VEN', 'TAN', 'SKT', 'ESW / SWA'], columns=['Sign'])
df_map.fillna(filler, inplace=True)
def continent_graph(continent="world",title=""):
    fig = px.choropleth(df_map, locations='Sign',
                       color='Billionaires',
                        hover_name='Country Name', 
                        color_continuous_scale="agsunset",
                        color_continuous_midpoint= 300,
                       scope = str(continent))
    layout = go.Layout(
        title=go.layout.Title(
            text= f"<b>{title}</b>",
            x=0.5
        ),
        showlegend=False,
        font=dict(size=13),
       width = 750,
        height = 350,
        margin=dict(l=0,r=0,b=0,t=30)
   )
    fig.update_layout(layout)
    fig.show()
continent_graph(continent='world', title='Worldwide Billionaires')
"""
**Note:** I took inspiration from the following notebook: https://www.kaggle.com/tahmidurrahmantabin/forbes-billionaires-2021
"""
"""
Thanks for reading my notebook. Feel free to upvote this notebook and leave comments!
"""