In [34]:
%matplotlib inline
import pandas as pd
import requests as req
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind, ttest_rel
np.set_printoptions(precision=3)
In [35]:
url = 'http://pt.wikipedia.org/wiki/Lista_de_unidades_federativas_do_Brasil_por_IDH'
In [36]:
html_text = req.get(url).text
In [37]:
table = pd.read_html(html_text, attrs={"class":"wikitable"})[0]
In [38]:
def idh_format(str):
num = float(str)/1000.0
return num
In [39]:
"""
0,800 – 1 (Muito alto) - idh_level = 0
0,700 - 0,799 (Alto) - idh_level = 0
0,600 - 0,699 (Médio) - idh_level = 1
0,500 - 0,599 (Baixo) - idh_level = 2
0 - 0,499 (Muito baixo)- idh_level = 3
"""
def idh_level(x):
if x >= 0.7:
return 0
elif 0.6 <= x < 0.7:
return 1
elif 0.5 <= x < 0.6:
return 2
elif 0.4 <= x < 0.5:
return 3
else: raise Exception("Invalid!")
"""
Abaixo da mediana de 2000 = level 0
Igual ou acima da mediana de 2000 = level 1
"""
def idh_level2(x):
if x >= table[4][2:].apply(idh_format).median():
return "ALTO"
else: return "BAIXO"
In [40]:
idhm_df = pd.DataFrame({u'Estado':table[2][2:].tolist(),u'I2010':table[3][2:].apply(idh_format).tolist(),u'I2000':table[4][2:].apply(idh_format).tolist()})
idhm_df["Ratio"] = idhm_df["I2010"]/idhm_df["I2000"]
idhm_df["idh_level_2000"] = idhm_df["I2000"].apply(idh_level2)
In [41]:
idhm_df
Out[41]:
In [42]:
idhm_df.describe()
Out[42]:
In [43]:
f = plt.figure(14)
idhm_df[["I2000","I2010","Ratio"]].hist(bins=15)
Out[43]:
In [44]:
ttest_rel(idhm_df['I2000'], idhm_df['I2010'])
Out[44]:
In [45]:
import scipy
import scikits.bootstrap as bootstrap
# compute 95% confidence intervals around the mean
CIs00 = bootstrap.ci(data=idhm_df["I2000"])
CIs10 = bootstrap.ci(data=idhm_df["I2010"])
CIsR = bootstrap.ci(data=idhm_df["Ratio"])
print("IDHM 2000 mean 95% confidence interval. Low={0:.3f}\tHigh={1:.3f}".format(*tuple(CIs00)))
print("IDHM 2010 mean 95% confidence interval. Low={0:.3f}\tHigh={1:.3f}".format(*tuple(CIs10)))
print("IDHM ratio mean 95% confidence interval. Low={0:.3f}\tHigh={1:.3f}".format(*tuple(CIsR)))
In [46]:
CIs00 = bootstrap.ci(data=idhm_df["I2000"], statfunction=scipy.median)
CIs10 = bootstrap.ci(data=idhm_df["I2010"], statfunction=scipy.median)
CIsR = bootstrap.ci(data=idhm_df["Ratio"], statfunction=scipy.median)
print("IDHM 2000 median 95% confidence interval. Low={0:.3f}\tHigh={1:.3f}".format(*tuple(CIs00)))
print("IDHM 2010 median 95% confidence interval. Low={0:.3f}\tHigh={1:.3f}".format(*tuple(CIs10)))
print("IDHM ratio median 95% confidence interval. Low={0:.3f}\tHigh={1:.3f}".format(*tuple(CIsR)))
A resposta de diversos testes, para um nível de 5% de significância, mostra que há fortes evidências que sim.
In [47]:
state_parties = pd.DataFrame({"Estado":idhm_df.Estado,"PT":np.repeat(0.0,27),"PSDB":np.repeat(0.0,27),"Outros":np.repeat(0.0,27)})
In [48]:
st_pa = np.array([
[u"Distrito Federal", 0.0, 0.0, 1.0],
[u"São Paulo", 0.0, 0.925, 0.075],
[u"Santa Catarina", 0.0, 0.0, 1.0],
[u"Rio de Janeiro", 0.4, 0.0, 0.6],
[u"Paraná", 0.0, 0.0, 1.0],
[u"Rio Grande do Sul", 0.2, 0.4, 0.4],
[u"Espírito Santo", 0.0, 0.2, 0.8],
[u"Goiás", 0.0, 0.6, 0.4],
[u"Minas Gerais", 0.0, 0.8, 0.2],
[u"Mato Grosso do Sul", 0.0, 0.6, 0.4],
[u"Mato Grosso", 0.0, 0.2, 0.8],
[u"Amapá", 0.075, 0.0, 0.925],
[u"Roraima", 0.275, 0.4, 0.325], # double check
[u"Tocantins", 0.0, 0.2, 0.8],
[u"Rondônia", 0.0, 0.4, 0.6],
[u"Rio Grande do Norte", 0.0, 0.0, 1.0],
[u"Ceará", 0.6, 0.0, 0.4],
[u"Amazonas", 0.0, 0.0, 1.0],
[u"Pernambuco", 0.0, 0.0, 1.0],
[u"Sergipe", 0.4, 0.2, 0.4],
[u"Acre", 1.0, 0.0, 0.0],
[u"Bahia", 0.4, 0.0, 0.6],
[u"Paraíba", 0.0, 0.55, 0.45],
[u"Piauí", 0.8, 0.0, 0.2],
[u"Pará", 0.4, 0.6, 0.0],
[u"Maranhão", 0.0, 0.0, 1.0],
[u"Alagoas", 0.0, 0.0, 1.0],
])
In [49]:
np.float64(st_pa[:,1:]).sum(axis=1)
Out[49]:
In [50]:
np.float64(st_pa[:,1:]).sum(axis=0)
Out[50]:
In [51]:
state_parties_df = pd.DataFrame({"Estado":st_pa[:,0],"PSDB":np.float64(st_pa[:,2]),"PT":np.float64(st_pa[:,1]),"Outros":np.float64(st_pa[:,3])})
In [52]:
state_parties_df
Out[52]:
In [53]:
df = idhm_df.merge(state_parties_df, on="Estado")
df
Out[53]:
In [54]:
sns.set()
sns.pairplot(df, hue="idh_level_2000", size=2.5)
Out[54]:
In [62]:
sns.coefplot("center(I2010) ~ PT + PSDB + Outros + C(idh_level_2000)", df, palette="Set1");
In [56]:
sns.coefplot("center(Ratio) ~ center(PT) + center(PSDB) + center(Outros) + C(idh_level_2000)", df, palette="Set1");
sns.coefplot("center(Ratio) ~ center(PT) + center(PSDB) + C(idh_level_2000)", df, palette="Set1");
sns.coefplot("center(Ratio) ~ center(PT) + center(PSDB) + C(idh_level_2000)", df, palette="Set1");
sns.coefplot("center(Ratio) ~ center(PT) + center(PSDB) + C(idh_level_2000)", df, palette="Set1");
In [57]:
from statsmodels.formula.api import ols
In [58]:
formula = "center(Ratio) ~ center(PT) + center(PSDB) + center(Outros) + C(idh_level_2000)"
model = ols(formula, df).fit()
model.summary()
Out[58]:
Não foi possível observar diferença significantiva entre os partidos.
Será que existe diferença para quem está acima da média de IDH?
In [59]:
sns.coefplot("center(Ratio) ~ center(PSDB) + center(PT) + center(Outros)",df[df.idh_level_2000=="ALTO"], palette="Set1");
sns.coefplot("center(Ratio) ~ center(PSDB) + center(PT)", df[df.idh_level_2000=="ALTO"], palette="Set1");
sns.coefplot("center(Ratio) ~ center(Outros) + center(PSDB)", df[df.idh_level_2000=="ALTO"], palette="Set1");
sns.coefplot("center(Ratio) ~ center(PSDB) + center(Outros)", df[df.idh_level_2000=="ALTO"], palette="Set1");
In [ ]:
formula = "scale(Ratio) ~ PT + PSDB"
model = ols(formula, df[df.idh_level_2000=="ALTO"]).fit()
model.summary()
Não foi possível identificar diferença nesse caso também.
Será que existe diferença então para quem está abaixo da média de IDH?
In [ ]:
sns.coefplot("center(Ratio) ~ center(PSDB) + center(PT) + center(Outros)",df[df.idh_level_2000=="BAIXO"], palette="Set1");
sns.coefplot("center(Ratio) ~ center(PSDB) + center(PT)", df[df.idh_level_2000=="BAIXO"], palette="Set1");
sns.coefplot("center(Ratio) ~ center(PT) + center(Outros)", df[df.idh_level_2000=="BAIXO"], palette="Set1");
sns.coefplot("center(Ratio) ~ center(PSDB) + center(Outros)", df[df.idh_level_2000=="BAIXO"], palette="Set1");
In [ ]:
formula = "scale(Ratio) ~ PT + PSDB"
model = ols(formula, df[df.idh_level_2000=="BAIXO"], ).fit()
model.summary()
Também não foi possível identificar diferença estatisticamente relevante.
TDB
In [ ]: