導入所需要的package
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
%matplotlib inline
plt.rcParams['font.sans-serif'] = ['KaiTi'] #中文
plt.rcParams['axes.unicode_minus'] = False #負號
數據清洗和讀取數據
df = pd.read_csv("energy.csv")
df.shape
###展示數據前6行
df.head(6)# 刪除特定的列 在數據中體現為 Unnamed: 0
df = df.drop(['Unnamed: 0'], axis=1)
df.head(6)
###重新命名列名稱 即簡化名稱
?
df.rename(columns={'Energy_type' : 'e_type', 'Energy_consumption' : 'e_con', 'Energy_production' : 'e_prod', 'Energy_intensity_per_capita' : 'ei_capita', 'Energy_intensity_by_GDP' : 'ei_gdp'}, inplace=True)df['e_type'] = df['e_type'].astype('category')df['e_type'] = df['e_type'].cat.rename_categories({'all_energy_types': 'all', 'natural_gas': 'nat_gas','petroleum_n_other_liquids': 'pet/oth','renewables_n_other': 'ren/oth'})df['e_type'] = df['e_type'].astype('object')df.info()
###對所以特征進行統計性描述
?
df.describe(include='all')
##得出每一種變量的總數
for var in df:print(f'{var}: {df[var].nunique()}')
###缺失值的處理
#先查看缺失值
for var in df:print(f'{var}: {df[var].isnull().sum()}')
從上面可以看到有的特征變量有很多缺失值
?由于大多數國家不消費或生產核能,因此缺少e_con和e_prod的許多價值,因此他們將其保留為Nan。我將添加 0 來代替這些
nuclear = df[df['e_type']=='nuclear']temp_ecp = df[df['e_type']!='nuclear']# Replacing all Nan values of e_con and e_prod of e_type nuclear to 0
nuclear[['e_con', 'e_prod']] = nuclear[['e_con', 'e_prod']].replace(np.nan, 0)# Joining them back up
df = pd.concat([nuclear, temp_ecp]).sort_index()
處理完之后再看,沒有缺失值了?
?現在可以開始查看數據了,可視化
?
從上圖可以看出分布高度右偏。
接下來查看能源類型分布?
###畫出其環形圖 看其分布和占比情況
percent = temp_dist['CO2_emission']
labels= temp_dist['e_type']my_pie,_,_ = plt.pie(percent, radius = 2.2, labels=labels, autopct="%.1f%%")
plt.setp(my_pie, width=0.6, edgecolor='white')
plt.show()
?
從上圖可以看出,所有能源都分布較為均勻
計算相關系數并畫出其熱力圖
?
不同可視化分析
with plt.rc_context(rc = {'figure.dpi': 250, 'axes.labelsize': 9,'xtick.labelsize': 10, 'ytick.labelsize': 10,'legend.title_fontsize': 7, 'axes.titlesize': 12,'axes.titlepad': 7}):# Data with only the 'World' valuescd = df[df['Country']=='World']fig, ax = plt.subplots(2, 2, figsize = (10, 7), # constrained_layout = True,gridspec_kw = {'width_ratios': [3, 3], 'height_ratios': [3, 3]})ax_flat = ax.flatten()### 1st graphsns.lineplot(ax=ax_flat[0], data=cd[cd['e_type']=='all'],x='Year', y='CO2_emission', lw=3).set_title('Global CO2 Emission Yearly (MMtonnes CO2)')### 2nd graphsns.lineplot(ax=ax_flat[1], data=cd[cd['e_type']!='all'],x='Year',y='CO2_emission',hue='e_type',lw=3,).set_title('Yearly CO2_emission for each e_type globally (MMtonnes CO2)')ax_flat[1].legend(fontsize=8, title='Energy Type', title_fontsize=9, loc='upper left', borderaxespad=0)ax_flat[1].tick_params(axis='x', rotation=35)### 3rd graphsns.lineplot(ax=ax_flat[2], data=cd,x='e_con', y='CO2_emission', lw=2).set_title('Relationship of global CO2 Emission and Energy Consumption')### 4th graphfor_dist = df[df['Country']!='World'][df['e_type']=='all']sns.distplot(for_dist['CO2_emission'], ax=ax_flat[3]).set_title('Density of CO2 Emission Globally')plt.tight_layout(pad = 1)plt.show()
?# 前 6 個國家/地區的年度二氧化碳排放量
fig, ax = plt.subplots(2, 3, figsize = (20, 10))# Top 6 Countries
countries = temp_cd['Country'].head(6)# Average CO2 Emission each year for top 6 emiters
for idx, (country, axes) in enumerate(zip(countries, ax.flatten())):cd3 = df[df['Country']==country][df['e_type']=='all']temp_data = cd3.groupby(['Year'])['CO2_emission'].sum().reset_index().sort_values(by='CO2_emission',ascending=False)plot_ = sns.barplot(ax=axes, data=temp_data, x='Year', y='CO2_emission', palette="Reds_d")# Titleaxes.set_title(country)# Reducing Density of X-ticksfor ind, label in enumerate(plot_.get_xticklabels()):if ind % 4 == 0: # every 10th label is keptlabel.set_visible(True)else:label.set_visible(False)# Rotating X axisfor tick in axes.get_xticklabels():tick.set_rotation(45)### Removing empty figures
else:[axes.set_visible(False) for axes in ax.flatten()[idx + 1:]]plt.tight_layout(pad=0.4, w_pad=2, h_pad=2)
plt.show()
?# 在此期間,中國和印度的排放量增加了很多。
#從這一時期開始到結束,二氧化碳排放量增加/減少幅度最大的國家
# 然后繪圖
# Countries with biggest increase in CO2 emission
Countries with biggest decrease in CO2 emission
結論
關于CO2排放量的結論
1.在此期間,二氧化碳排放量一直在增加。
2.煤炭和石油/其他液體一直是這一時期的主要能源。
3.二氧化碳排放量平均每年增長1.71%,整個時期整體增長68.14%。
4.截至2019年,當年平均二氧化碳排放量為10.98(百萬噸二氧化碳)。
5.在整個時期,二氧化碳排放量最大的國家是中國和美國,這兩個國家的二氧化碳排放量幾乎是其他國家的4倍或更多。
6.在此期間,中國和印度的二氧化碳排放量增加是其他所有國家中最多的。
7.在此期間,前蘇聯加盟共和國的二氧化碳排放量下降幅度最大,英國和德國的排放量也略有下降。
8.一般來說,人口越多,該國排放的二氧化碳就越多。
9.GDP越大,該國二氧化碳排放量越大。
10.一個國家的能源消耗越大,二氧化碳排放量就越大。
11.按人均能源強度的GDP計算的高或低能源強度并不一定能預測大量的二氧化碳排放量,但一般來說,它越低越好(節約的能量越多意味著二氧化碳排放量越少)。
代碼和數據
創作不易,希望大家多多點贊收藏和評論!