IDH


In [15]:
%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
from scipy.stats import gaussian_kde
from statsmodels.formula.api import ols, mixedlm, gee
from statsmodels.stats.outliers_influence import OLSInfluence
from statsmodels.regression.linear_model import OLSResults
from patsy import dmatrix

np.set_printoptions(precision=3)

Carregando dados de IDH-M da Wikipedia


In [16]:
idhm_df = pd.read_csv("../data/brazil_states_idhl_2000_2010.csv", index_col=0)
idhm_df


Out[16]:
Estado I2000 I2010 Ratio idh_level_2000
0 Distrito Federal 0.814 0.873 1.072482 1
1 Santa Catarina 0.812 0.860 1.059113 1
2 São Paulo 0.786 0.845 1.075064 1
3 Rio Grande do Sul 0.804 0.840 1.044776 1
4 Minas Gerais 0.759 0.838 1.104084 1
5 Rio de Janeiro 0.740 0.835 1.128378 1
6 Espírito Santo 0.777 0.835 1.074646 1
7 Mato Grosso do Sul 0.752 0.833 1.107713 1
8 Paraná 0.747 0.830 1.111111 1
9 Goiás 0.773 0.827 1.069858 1
10 Mato Grosso 0.740 0.821 1.109459 1
11 Amapá 0.711 0.813 1.143460 0
12 Roraima 0.717 0.809 1.128312 0
13 Amazonas 0.692 0.805 1.163295 0
14 Rondônia 0.688 0.800 1.162791 0
15 Ceará 0.713 0.793 1.112202 0
16 Tocantins 0.688 0.793 1.152616 0
17 Rio Grande do Norte 0.700 0.792 1.131429 0
18 Pernambuco 0.705 0.789 1.119149 0
19 Pará 0.725 0.789 1.088276 1
20 Bahia 0.680 0.783 1.151471 0
21 Paraíba 0.672 0.783 1.165179 0
22 Sergipe 0.678 0.781 1.151917 0
23 Piauí 0.676 0.777 1.149408 0
24 Acre 0.694 0.777 1.119597 0
25 Maranhão 0.649 0.757 1.166410 0
26 Alagoas 0.647 0.755 1.166924 0

Análise


In [17]:
idhm_df.describe()


Out[17]:
I2000 I2010 Ratio idh_level_2000
count 27.000000 27.000000 27.000000 27.000000
mean 0.723667 0.808630 1.119597 0.444444
std 0.048339 0.030475 0.036550 0.506370
min 0.647000 0.755000 1.044776 0.000000
25% 0.688000 0.786000 1.096180 0.000000
50% 0.713000 0.805000 1.119597 0.000000
75% 0.755500 0.834000 1.151694 1.000000
max 0.814000 0.873000 1.166924 1.000000

In [18]:
f = plt.figure(14)
idhm_df[["I2000","I2010","Ratio"]].hist(bins=10)
plt.figure()
sns.kdeplot(idhm_df["I2000"], shade=True);
sns.kdeplot(idhm_df["I2010"], shade=True);
sns.kdeplot(idhm_df["Ratio"], shade=True);


<matplotlib.figure.Figure at 0x7f972dd83b38>

Testando hipótese

A diferença média entre os IDHs de 2000 e 2010 é estatisticamente significativa?


In [19]:
ttest_rel(idhm_df['I2000'], idhm_df['I2010'])


Out[19]:
(-20.221372506332678, 1.9871191986090549e-17)

In [20]:
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)))


IDHM 2000 mean 95% confidence interval. Low=0.707	High=0.743
IDHM 2010 mean 95% confidence interval. Low=0.798	High=0.820
IDHM ratio mean 95% confidence interval. Low=1.105	High=1.133

In [21]:
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)))


IDHM 2000 median 95% confidence interval. Low=0.688	High=0.740
IDHM 2010 median 95% confidence interval. Low=0.789	High=0.827
IDHM ratio median 95% confidence interval. Low=1.104	High=1.143

A resposta de diversos testes, para um nível de 5% de significância, mostra que há fortes evidências que sim.

Montando percentual de impacto da administração de cada partido em cada Estado da Federação.


In [22]:
state_parties_df = pd.read_csv("../data/brazil_states_parties_2000-2010.csv", index_col=0)

In [23]:
state_parties_df


Out[23]:
Estado Outros PSDB PT
0 Distrito Federal 1.000 0.000 0.000
1 São Paulo 0.075 0.925 0.000
2 Santa Catarina 1.000 0.000 0.000
3 Rio de Janeiro 0.600 0.000 0.400
4 Paraná 1.000 0.000 0.000
5 Rio Grande do Sul 0.400 0.400 0.200
6 Espírito Santo 0.800 0.200 0.000
7 Goiás 0.400 0.600 0.000
8 Minas Gerais 0.200 0.800 0.000
9 Mato Grosso do Sul 0.400 0.600 0.000
10 Mato Grosso 0.800 0.200 0.000
11 Amapá 0.925 0.000 0.075
12 Roraima 0.325 0.400 0.275
13 Tocantins 0.800 0.200 0.000
14 Rondônia 0.600 0.400 0.000
15 Rio Grande do Norte 1.000 0.000 0.000
16 Ceará 0.400 0.000 0.600
17 Amazonas 1.000 0.000 0.000
18 Pernambuco 1.000 0.000 0.000
19 Sergipe 0.400 0.200 0.400
20 Acre 0.000 0.000 1.000
21 Bahia 0.600 0.000 0.400
22 Paraíba 0.450 0.550 0.000
23 Piauí 0.200 0.000 0.800
24 Pará 0.000 0.600 0.400
25 Maranhão 1.000 0.000 0.000
26 Alagoas 1.000 0.000 0.000

In [24]:
state_regions_df = pd.read_csv("../data/brazil_states_regions.csv", index_col=0)
state_regions_df


Out[24]:
Estado Regiao
0 Distrito Federal Centro-Oeste
1 São Paulo Sudeste
2 Santa Catarina Sul
3 Rio de Janeiro Sudeste
4 Paraná Sul
5 Rio Grande do Sul Sul
6 Espírito Santo Sudeste
7 Goiás Centro-Oeste
8 Minas Gerais Sudeste
9 Mato Grosso do Sul Centro-Oeste
10 Mato Grosso Centro-Oeste
11 Amapá Norte
12 Roraima Norte
13 Tocantins Norte
14 Rondônia Norte
15 Rio Grande do Norte Nordeste
16 Ceará Nordeste
17 Amazonas Norte
18 Pernambuco Nordeste
19 Sergipe Nordeste
20 Acre Norte
21 Bahia Nordeste
22 Paraíba Nordeste
23 Piauí Nordeste
24 Pará Norte
25 Maranhão Nordeste
26 Alagoas Nordeste

In [25]:
df = idhm_df.merge(state_parties_df, on="Estado")
df = df.merge(state_regions_df, on="Estado")
df


Out[25]:
Estado I2000 I2010 Ratio idh_level_2000 Outros PSDB PT Regiao
0 Distrito Federal 0.814 0.873 1.072482 1 1.000 0.000 0.000 Centro-Oeste
1 Santa Catarina 0.812 0.860 1.059113 1 1.000 0.000 0.000 Sul
2 São Paulo 0.786 0.845 1.075064 1 0.075 0.925 0.000 Sudeste
3 Rio Grande do Sul 0.804 0.840 1.044776 1 0.400 0.400 0.200 Sul
4 Minas Gerais 0.759 0.838 1.104084 1 0.200 0.800 0.000 Sudeste
5 Rio de Janeiro 0.740 0.835 1.128378 1 0.600 0.000 0.400 Sudeste
6 Espírito Santo 0.777 0.835 1.074646 1 0.800 0.200 0.000 Sudeste
7 Mato Grosso do Sul 0.752 0.833 1.107713 1 0.400 0.600 0.000 Centro-Oeste
8 Paraná 0.747 0.830 1.111111 1 1.000 0.000 0.000 Sul
9 Goiás 0.773 0.827 1.069858 1 0.400 0.600 0.000 Centro-Oeste
10 Mato Grosso 0.740 0.821 1.109459 1 0.800 0.200 0.000 Centro-Oeste
11 Amapá 0.711 0.813 1.143460 0 0.925 0.000 0.075 Norte
12 Roraima 0.717 0.809 1.128312 0 0.325 0.400 0.275 Norte
13 Amazonas 0.692 0.805 1.163295 0 1.000 0.000 0.000 Norte
14 Rondônia 0.688 0.800 1.162791 0 0.600 0.400 0.000 Norte
15 Ceará 0.713 0.793 1.112202 0 0.400 0.000 0.600 Nordeste
16 Tocantins 0.688 0.793 1.152616 0 0.800 0.200 0.000 Norte
17 Rio Grande do Norte 0.700 0.792 1.131429 0 1.000 0.000 0.000 Nordeste
18 Pernambuco 0.705 0.789 1.119149 0 1.000 0.000 0.000 Nordeste
19 Pará 0.725 0.789 1.088276 1 0.000 0.600 0.400 Norte
20 Bahia 0.680 0.783 1.151471 0 0.600 0.000 0.400 Nordeste
21 Paraíba 0.672 0.783 1.165179 0 0.450 0.550 0.000 Nordeste
22 Sergipe 0.678 0.781 1.151917 0 0.400 0.200 0.400 Nordeste
23 Piauí 0.676 0.777 1.149408 0 0.200 0.000 0.800 Nordeste
24 Acre 0.694 0.777 1.119597 0 0.000 0.000 1.000 Norte
25 Maranhão 0.649 0.757 1.166410 0 1.000 0.000 0.000 Nordeste
26 Alagoas 0.647 0.755 1.166924 0 1.000 0.000 0.000 Nordeste

In [26]:
sns.factorplot("idh_level_2000","Ratio",data=df, kind="box")


Out[26]:
<seaborn.axisgrid.FacetGrid at 0x7f972de308d0>

In [27]:
sns.factorplot("Regiao","Ratio",data=df, kind="box")


Out[27]:
<seaborn.axisgrid.FacetGrid at 0x7f972eaf39e8>

In [28]:
sns.set()
sns.pairplot(df, hue="idh_level_2000", size=2.5)


Out[28]:
<seaborn.axisgrid.PairGrid at 0x7f972e834940>

In [29]:
sns.coefplot("Ratio ~ PT + PSDB + Outros + C(idh_level_2000) - 1", df, palette="Set1");



In [30]:
sns.coefplot("Ratio ~ Outros==0 + Outros - 1", df, palette="Set1");



In [31]:
sns.set(style="whitegrid")
sns.residplot(df.Outros,df.Ratio, color="navy", lowess=True, order=1)


Out[31]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f97261f75f8>

In [32]:
sns.coefplot("Ratio ~ PT==0 + PT - 1", df, palette="Set1");



In [33]:
sns.set(style="whitegrid")
sns.residplot(df[df.PT>0].PT, df[df.PT>0].Ratio, color="navy", order=1)


Out[33]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f9725fd5a90>

In [34]:
sns.coefplot("Ratio ~ PSDB==0 + PSDB + np.multiply(PSDB, PSDB) - 1", df, palette="Set1");



In [35]:
sns.set(style="whitegrid")
sns.residplot(df[df.PSDB>0].PSDB, df[df.PSDB>0].Ratio, color="navy", lowess=True, order=2)


Out[35]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f9725f7b208>

Impacto por partido ou nível do IDH-M em 2000


In [36]:
sns.coefplot("Ratio ~ PT + PSDB + Outros + C(idh_level_2000) - 1", df, palette="Set1");
sns.coefplot("Ratio ~ PT + PSDB + C(idh_level_2000)", df, palette="Set1");
sns.coefplot("Ratio ~ PT + Outros + C(idh_level_2000)", df, palette="Set1");
sns.coefplot("Ratio ~ PSDB + Outros + C(idh_level_2000)", df, palette="Set1");



In [37]:
formula = "Ratio ~ PT + PSDB + C(idh_level_2000) + C(Regiao)"
model = ols(formula, df).fit()
model.summary()


Out[37]:
OLS Regression Results
Dep. Variable: Ratio R-squared: 0.715
Model: OLS Adj. R-squared: 0.611
Method: Least Squares F-statistic: 6.822
Date: Wed, 20 May 2015 Prob (F-statistic): 0.000396
Time: 00:10:32 Log-Likelihood: 68.507
No. Observations: 27 AIC: -121.0
Df Residuals: 19 BIC: -110.6
Df Model: 7
Covariance Type: nonrobust
coef std err t P>|t| [95.0% Conf. Int.]
Intercept 1.1414 0.027 41.627 0.000 1.084 1.199
C(idh_level_2000)[T.1] -0.0469 0.026 -1.775 0.092 -0.102 0.008
C(Regiao)[T.Nordeste] 0.0114 0.030 0.387 0.703 -0.050 0.073
C(Regiao)[T.Norte] 0.0111 0.027 0.407 0.689 -0.046 0.068
C(Regiao)[T.Sudeste] 0.0097 0.016 0.591 0.562 -0.025 0.044
C(Regiao)[T.Sul] -0.0195 0.018 -1.089 0.290 -0.057 0.018
PT -0.0235 0.018 -1.310 0.206 -0.061 0.014
PSDB -0.0131 0.019 -0.677 0.506 -0.054 0.027
Omnibus: 3.274 Durbin-Watson: 1.905
Prob(Omnibus): 0.195 Jarque-Bera (JB): 1.394
Skew: 0.012 Prob(JB): 0.498
Kurtosis: 1.887 Cond. No. 15.1

Não foi possível observar diferença significantiva entre os partidos.

Quais estados possuem diferença significativa?

Comparando 2010 com 2000


In [38]:
sns.lmplot("I2000", "I2010", data=df, legend=True, size=10, n_boot=10000, ci=95)


Out[38]:
<seaborn.axisgrid.FacetGrid at 0x7f9725c7a6d8>

In [39]:
sns.jointplot("I2000", "I2010", data=df, kind='resid',color=sns.color_palette()[2], size=10)


Out[39]:
<seaborn.axisgrid.JointGrid at 0x7f9725bd8908>

In [40]:
sns.coefplot("I2010 ~ I2000", data=df, intercept=True)
sns.coefplot("I2010 ~ I2000", data=df, groupby="idh_level_2000", intercept=True)



In [41]:
sns.lmplot("I2000", "I2010", data=df, hue="idh_level_2000", col="idh_level_2000", legend=True, size=6, n_boot=10000, ci=99)
sns.lmplot("I2000", "I2010", data=df, hue="Regiao", col="Regiao", col_wrap=2, legend=True, size=6, n_boot=10000, ci=99)


Out[41]:
<seaborn.axisgrid.FacetGrid at 0x7f97258cbba8>

In [42]:
md = ols("I2010 ~ I2000 + C(Regiao)", df).fit()
print(md.summary())


                            OLS Regression Results                            
==============================================================================
Dep. Variable:                  I2010   R-squared:                       0.918
Model:                            OLS   Adj. R-squared:                  0.898
Method:                 Least Squares   F-statistic:                     46.72
Date:                Wed, 20 May 2015   Prob (F-statistic):           1.13e-10
Time:                        00:10:46   Log-Likelihood:                 90.137
No. Observations:                  27   AIC:                            -168.3
Df Residuals:                      21   BIC:                            -160.5
Df Model:                           5                                         
Covariance Type:            nonrobust                                         
=========================================================================================
                            coef    std err          t      P>|t|      [95.0% Conf. Int.]
-----------------------------------------------------------------------------------------
Intercept                 0.4809      0.067      7.172      0.000         0.341     0.620
C(Regiao)[T.Nordeste]    -0.0179      0.010     -1.838      0.080        -0.038     0.002
C(Regiao)[T.Norte]       -0.0091      0.008     -1.073      0.295        -0.027     0.009
C(Regiao)[T.Sudeste]      0.0017      0.007      0.250      0.805        -0.013     0.016
C(Regiao)[T.Sul]         -0.0035      0.008     -0.459      0.651        -0.019     0.012
I2000                     0.4646      0.087      5.347      0.000         0.284     0.645
==============================================================================
Omnibus:                        1.993   Durbin-Watson:                   1.548
Prob(Omnibus):                  0.369   Jarque-Bera (JB):                1.714
Skew:                          -0.583   Prob(JB):                        0.424
Kurtosis:                       2.595   Cond. No.                         77.6
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

In [43]:
rrr = md.get_robustcov_results()
rrp = rrr.outlier_test("fdr_bh", 0.1)
idx = rrp[rrp["fdr_bh(p)"] <= 0.1].index
print("Estados fora da média:\n",df.ix[idx.values])
rrp[rrp["fdr_bh(p)"] <= 0.1]


Estados fora da média:
 Empty DataFrame
Columns: [Estado, I2000, I2010, Ratio, idh_level_2000, Outros, PSDB, PT, Regiao]
Index: []
Out[43]:
student_resid unadj_p fdr_bh(p)

GEE


In [44]:
import statsmodels.api as sm
md = gee("Ratio ~ PT + PSDB ", df.idh_level_2000, df, cov_struct=sm.cov_struct.Exchangeable()) 
mdf = md.fit() 
print(mdf.summary())
print(mdf.cov_struct.summary())


                               GEE Regression Results                              
===================================================================================
Dep. Variable:                       Ratio   No. Observations:                   27
Model:                                 GEE   No. clusters:                        2
Method:                        Generalized   Min. cluster size:                  12
                      Estimating Equations   Max. cluster size:                  15
Family:                           Gaussian   Mean cluster size:                13.5
Dependence structure:         Exchangeable   Num. iterations:                     6
Date:                     Wed, 20 May 2015   Scale:                           0.001
Covariance type:                    robust   Time:                         00:10:46
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept      1.1201      0.022     51.375      0.000         1.077     1.163
PT            -0.0176      0.011     -1.675      0.094        -0.038     0.003
PSDB          -0.0032      0.005     -0.613      0.540        -0.014     0.007
==============================================================================
Skew:                         -0.4534   Kurtosis:                      -1.0136
Centered skew:                -0.0966   Centered kurtosis:             -0.7094
==============================================================================
The correlation between two observations in the same cluster is 0.598

In [45]:
plt.plot(mdf.fittedvalues, mdf.resid, 'o', alpha=0.5)
plt.xlabel("Fitted values", size=17)
plt.ylabel("Residuals", size=17)


Out[45]:
<matplotlib.text.Text at 0x7f97259a9320>

In [46]:
sns.jointplot(mdf.fittedvalues, mdf.resid, size=10, kind="kde")


Out[46]:
<seaborn.axisgrid.JointGrid at 0x7f9725b0e358>

In [ ]:


In [ ]: