使用statsmodels或scipy的pandas数据框在python中进行方差分析? [英] ANOVA in python using pandas dataframe with statsmodels or scipy?

查看:516
本文介绍了使用statsmodels或scipy的pandas数据框在python中进行方差分析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Pandas数据框细分一个变量中的方差.

I want to use the Pandas dataframe to breakdown the variance in one variable.

例如,如果我有一个名为"Degrees"的列,并且为不同的日期,城市以及夜晚与白天之间建立了索引,那么我想找出该系列中变异的哪一部分来自于十字架截面城市变化,多少来自时间序列变化,多少来自夜晚与白天.

For example, if I have a column called 'Degrees', and I have this indexed for various dates, cities, and night vs. day, I want to find out what fraction of the variation in this series is coming from cross-sectional city variation, how much is coming from time series variation, and how much is coming from night vs. day.

在Stata中,我将使用固定效果并查看R ^ 2.希望我的问题有道理.

In Stata I would use Fixed effects and look at the R^2. Hopefully my question makes sense.

基本上,我想做的是通过其他三列找到ANOVA对度数"的细分.

Basically, what I want to do, is find the ANOVA breakdown of "Degrees" by three other columns.

推荐答案

我建立了直接比较以测试他们,发现他们的假设可以

I set up a direct comparison to test them, found that their assumptions can differ slightly , got a hint from a statistician, and here is an example of ANOVA on a pandas dataframe matching R's results:

import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols


# R code on R sample dataset

#> anova(with(ChickWeight, lm(weight ~ Time + Diet)))
#Analysis of Variance Table
#
#Response: weight
#           Df  Sum Sq Mean Sq  F value    Pr(>F)
#Time        1 2042344 2042344 1576.460 < 2.2e-16 ***
#Diet        3  129876   43292   33.417 < 2.2e-16 ***
#Residuals 573  742336    1296
#write.csv(file='ChickWeight.csv', x=ChickWeight, row.names=F)

cw = pd.read_csv('ChickWeight.csv')

cw_lm=ols('weight ~ Time + C(Diet)', data=cw).fit() #Specify C for Categorical
print(sm.stats.anova_lm(cw_lm, typ=2))
#                  sum_sq   df            F         PR(>F)
#C(Diet)    129876.056995    3    33.416570   6.473189e-20
#Time      2016357.148493    1  1556.400956  1.803038e-165
#Residual   742336.119560  573          NaN            NaN

这篇关于使用statsmodels或scipy的pandas数据框在python中进行方差分析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆