数据来源:
去到 https://stats.oecd.org/index.aspx?DataSetCode=BLI 下载数据,命名为BLI.csv 储存到notebook 创建的第一个项目相同的路径
去 http://goo.gl/j1MSKe 下载2015世界各国人均GDP数据,命名为WEO_Data.xls, 储存到相同路径
结果为bool值
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sklearn# Load the data
oecd_bli = pd.read_csv("BLI.csv", thousands=',') #导入幸福指数文件,thousand是指若出现1000以上的数据去掉数字中的逗号,只保留数字
gdp_per_capita = pd.read_csv("gdp.csv",thousands=',',delimiter='\t',encoding='latin1', na_values="n/a")
#读取gdp数据,delimiter意为以制表符为分割,encoding指定编码方式,na_value读取到数据时,格式改为dataform中的na格式
oecd_bli.head() #将载入的幸福指数展现出来def prepare_country_stats(oecd_bli, gdp_per_capita):oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"]#取列名称为INEQUALITY里面元素为TOT那一行所有的元素oecd_bli = oecd_bli.pivot(index="Country",columns="Indicator",value="Value")print(oecd_bli.head(1))gdp_per_capite.rename(columns={"2015":"GDP per capita"},inplace=True)#将2015列名改为GDP per capita,inplace=true表示在原来的数据中修改,若等于false则会有一个返回值gdp_per_capite.set_index("Country",inplace=True)#country列变成一个索引的形式full_country_stats = pd.merge(left=oecd_bli,right=gdp_per_capite,left_index=True,right_index=True)#merge连接函数,以country为媒介,left取oecd_bli,right同理取gdp_per_capite,index=true表示都保留原来的indexfull_country_stats.sort_values(by="GDP per capita",inplace=True)#根据GDP per capita的值进行排序,默认从小到大排列remove_indices = [0,1,6,8,33,34,35]#移除空的索引keep_indices = list(set(range(36)) - set(remove_indices))#前36个国家里面减去空的索引return full_country_stats[["GDP per capita",'Life satisfaction']].iloc[keep_indices]#iloc切片,保留下来两列数据# Prepare the data
country_stats = prepare_country_stats(oecd_bli, gdp_per_capita)
#调用函数
X = np.c_[country_stats["GDP per capita"]]
y = np.c_[country_stats["Life satisfaction"]]
#np.c_把数据中这一列转化称为numpy底下的array形式# Visualize the data
country_stats.plot(kind='scatter', x="GDP per capita", y='Life satisfaction')
plt.show()
#画散点图# Select a linear model
from sklearn import linear_model
lin_reg_model = sklearn.linear_model.LinearRegression()
#引用模型,一个实例# Train the model
lin_reg_model.fit(X, y)# Make a prediction for Cyprus
X_new = [[22587]] # Cyprus' GDP per capita
print(lin_reg_model.predict(X_new)) # outputs [[ 5.96242338]]
#用新的二维数组进行预测
连接结果
sort函数
如果直接拿的话,格式不是一个矩阵类型
但对它进行操作之后