-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
202 lines (169 loc) · 7.56 KB
/
main.py
File metadata and controls
202 lines (169 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# Import libraries
import streamlit as st
import pandas as pd
from streamlit_searchbox import st_searchbox
from typing import List
import plotly.express as px
import flagpy as fp
from PIL import Image
from utils.styles import styles
st.set_page_config(
page_title="World Happiness Report,2015 up to 2022",
)
# css part
st.write(styles, unsafe_allow_html=True)
@st.cache_data
def get_data():
dataframe = pd.read_csv(
'./world_happiness_2015_2022/world-happiness-report-2015-2022.csv')
flags_df = fp.get_flag_df()
countires = set(dataframe["Country"])
regions = set(dataframe["Region"])
return dataframe, countires, flags_df, regions
@st.cache_data
def get_desc_by_country(dataframe):
return dataframe.groupby('Country')['Happiness Rank'].describe()
def check_flag(country_name):
flag_name_converter = {'Dominican Republic': 'The Dominican Republic', 'United Arab Emirates': 'The United Arab Emirates',
'United Kingdom': 'The United Kingdom', 'United States': 'The United States'}
country_name = flag_name_converter.get(country_name, country_name)
if country_name in fp.get_country_list():
return True, country_name
return False, country_name
def search_by_country(searchterm: str) -> List[any]:
global countries
return [c for c in countries if c.lower().startswith(searchterm.lower())] if searchterm else []
overall_df, countries, flags_df, regions = get_data()
check_boxes = {}
with st.sidebar:
selected_country = st_searchbox(
search_function=search_by_country,
key="country_searchbox",
placeholder="Search for a Country",
)
if not selected_country:
st.markdown('<b>Filter By Region</b><hr/>', unsafe_allow_html=True)
c9, c10 = st.columns([0.5, 0.5])
for index, cb in enumerate(regions):
if index % 2 == 0:
with c9:
check_box = st.checkbox(cb)
else:
with c10:
check_box = st.checkbox(cb)
check_boxes[cb] = check_box
overall_df = overall_df.loc[:, ~overall_df.columns.str.contains('^Unnamed')]
if all(not value for value in check_boxes.values()):
check_boxes['All'] = True
else:
check_boxes['All'] = False
if selected_country:
col1, col2 = st.columns([0.5, 0.5])
col3, col4 = st.columns([0.5, 0.5])
with col1:
st.write(selected_country)
with col2:
signal, country_name = check_flag(selected_country)
if signal:
img = Image.fromarray(flags_df["flag"].loc[country_name], 'RGB')
img.save('flag.png')
img = Image.fromarray(flags_df["flag"].loc[country_name], 'RGB')
with Image.open('./flag.png') as image:
st.image(image)
df_by_selected_country = overall_df[overall_df.Country == selected_country]
df_by_selected_country = df_by_selected_country.sort_values(
by=["Year"], ascending=True)
st.dataframe(df_by_selected_country.set_index(overall_df.columns[10]))
with col3:
st.write('Best Rank:', df_by_selected_country.loc[df_by_selected_country['Happiness Rank'].idxmin(
)]['Happiness Rank'])
with col4:
st.write('Worst Rank:', df_by_selected_country.loc[df_by_selected_country['Happiness Rank'].idxmax(
)]['Happiness Rank'])
difference = df_by_selected_country.loc[df_by_selected_country['Year'].idxmin(
)]['Happiness Rank'] - df_by_selected_country.loc[df_by_selected_country['Year'].idxmax()]['Happiness Rank']
st.write(f"""Difference from <b>{df_by_selected_country.loc[df_by_selected_country['Year'].idxmin()]['Year']}</b> until
<b>{df_by_selected_country.loc[df_by_selected_country['Year'].idxmax()]['Year']}</b> :
<b style="color: {'green' if difference > 0 else 'gray' if difference == 0 else 'red'}">{"%+d" % (difference)}</b>""", unsafe_allow_html=True)
fig = px.line(df_by_selected_country, x="Year",
y="Happiness Rank", title=f"Year / Happiness Rank")
st.plotly_chart(fig)
else:
selected_year = st.selectbox(
'Choose The Year',
(str(year) for year in range(2015, 2023)))
st.markdown(
f"You Selected Year: <b>{selected_year}</b>", unsafe_allow_html=True)
df = overall_df[overall_df.Year == int(selected_year)]
try:
if not check_boxes['All']:
filtered_region = list(
filter(lambda k: check_boxes[k], check_boxes))
st.write(
f'<b>Filters:</b> <br/><span class="c-pill c-pill--warning">{",".join(filtered_region)}</span>', unsafe_allow_html=True)
df = df[df['Region'].isin(filtered_region)]
except KeyError:
pass
# Happiness Rank Column as Index
df = df.sort_values(by=["Happiness Rank"], ascending=True)
if df.shape[0] > 0:
st.dataframe(df.set_index(df.columns[0]))
c5, c6 = st.columns([0.5, 0.5])
with c5:
x_list = list(df.columns) + ['Happiness Score']
x_list.remove('Generosity')
x_axis = st.selectbox(
'Choose X axis criterion',
(f'x: {cri}' for cri in x_list[::-1]))
with c6:
y_list = list(df.columns) + ['Generosity']
y_list.remove('Generosity')
y_axis = st.selectbox(
'Choose Y axis criterion',
(f'y: {cri}' for cri in y_list[::-1]))
try:
try:
corr = round(df[x_axis.replace('x: ', '')].apply(lambda x: float(x.split()[0].replace(',', ''))).corr(
df[y_axis.replace('y: ', '')].apply(lambda x: float(x.split()[0].replace(',', '')))), 2)
except AttributeError:
corr = round(df[x_axis.replace('x: ', '')].astype(float).corr(
df[y_axis.replace('y: ', '')].astype(float)), 2)
if str(corr) != "nan":
st.markdown(f"Correlation between <b>{x_axis.replace('x: ','')}</b> and <b>{y_axis.replace('y: ','')}</b> is : <b>{corr}</b>",
unsafe_allow_html=True)
except ValueError:
print("Error catched")
pass
fig = px.scatter(df, x=x_axis.replace('x: ', ''),
y=y_axis.replace('y: ', ''), title=f"{x_axis.replace('x: ','')} / {y_axis.replace('y: ','')}")
st.plotly_chart(fig)
st.header('Happiness Rank over 2015 until 2022')
try:
if not check_boxes['All']:
st.dataframe(overall_df[overall_df['Region'].isin(filtered_region)].groupby(
'Country')['Happiness Rank'].describe())
else:
st.dataframe(get_desc_by_country(overall_df))
except KeyError:
pass
st.write("""<small>
<b>Count:</b> It refers to the count number of observations (for example: Afghanistan 8 times and Angola 4 times from 2015 until 2022)
<br/>
<b>Mean:</b> The average rank
<br/>
<b>Std:</b> The standard deviation
<br/>
<b>Min:</b> Lowest Rank
<br/>
<b>25%:</b> The 25% percentile
<br/>
<b>50%:</b> The 50% percentile
<br/>
<b>75%:</b> The 75% percentile
<br/>
<b>Max:</b> Highest Rank
</small>
""", unsafe_allow_html=True)
else:
st.markdown("<b>No Data, Please Change Filters</b>",
unsafe_allow_html=True)