Weather statistics by country

Now, let's generate a model to show the top 20 countries with the greatest temperature difference. As always, the first step is to import the .CSV file. By now, you must be familiar with the pattern. We have already created a DataFrame in the preceding example. To keep the modeling simple, we will be reimporting the .CSV file under a different DataFrame name:

tempByCountry = pd.read_csv('GlobalLandTemperaturesByCountry.csv')
countries = tempByCountry['Country'].unique()

Now, to visualize the data, we are going to use another Python package, called seaborn (https://seaborn.pydata.org/). We can import the package as follows:

import seaborn as sns

Now, let's get the minimum and maximum temperature lists:

max_min_list = []

# getting max and min temperatures
for country in countries:
curr_temps = tempByCountry[tempByCountry['Country'] == country]['AverageTemperature']
max_min_list.append((curr_temps.max(), curr_temps.min()))

There are some NaN values. Let's clean those values:

# NaN cleaning
res_max_min_list = []
res_countries = []

for i in range(len(max_min_list)):
if not np.isnan(max_min_list[i][0]):
res_max_min_list.append(max_min_list[i])
res_countries.append(countries[i])

Once the data is cleaned, let's calculate the difference:

# calculating the differences 
differences = []

for tpl in res_max_min_list:
differences.append(tpl[0] - tpl[1])

We have the differences in the differences array. We can sort it out so that we can extract the top 20 entries. We can do that with the following: 

# sorting the result
differences, res_countries = (list(x) for x in zip(*sorted(zip(differences, res_countries), key=lambda pair: pair[0], reverse=True)))

Finally, let's plot the chart:

# ploting the chart
f, ax = plt.subplots(figsize=(8, 8))
sns.barplot(x=differences[:20], y=res_countries[:20], palette=sns.color_palette("coolwarm", 25), ax=ax)

texts = ax.set(ylabel="", xlabel="Temperature difference", title="Countries with the highest temperature differences")

We should have a nice chart now:

Screenshot 14.7: Top 20 countries with the greatest temperature difference
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset