Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据特定变量计算每行和分组的标准偏差_Python_Pandas_Group By_Statistics_Standard Deviation - Fatal编程技术网

Python 根据特定变量计算每行和分组的标准偏差

Python 根据特定变量计算每行和分组的标准偏差,python,pandas,group-by,statistics,standard-deviation,Python,Pandas,Group By,Statistics,Standard Deviation,我是python的新用户,我的问题是计算列残差的标准偏差。 要做到这一点: 我必须计算每组的平均残差 我需要每个组的ID大小 我碰巧做了一些计算,这是我的代码: import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as sm from statistics import stdev import statistics from math import * #Enumerate the

我是python的新用户,我的问题是计算列残差的标准偏差。 要做到这一点:

  • 我必须计算每组的平均残差
  • 我需要每个组的ID大小
  • 我碰巧做了一些计算,这是我的代码:

    import pandas as pd 
    import statsmodels.api as sm
    import statsmodels.formula.api as sm
    from statistics import stdev
    import statistics
    from math import * 
    
    #Enumerate the data 1,2,3.. for each variable 
    A['Rec'] = A.groupby(['code ']).cumcount().add(1)
    
    ## Defining companies by their IDs
    A['ID']=A.groupby('code ').ngroup().add(1)
    
    ### FINDING RESIDUALS 
    results = sm.ols(formula='Y ~ X', data=A).fit()
    Y_pred = results.predict(A[["X"]])
    Y_pred
    A['residual'] = A["Y"].values-Y_pred
    
    ###SIZE 
    A['size']=A.groupby(['ID']).size()
    
    
    
    ###SD of residuals
    for i in A['ID']:
        A['Std'] = sqrt((A['residual']-A['MEAN'])**2)/(A['size']-1)))
    
    这是我的数据帧


    这些组现在被称为ID(1,2,3,4,5);每个组中都有行。在每一行和分组中,我希望得到列剩余的SD。

    我很抱歉,因为我没有足够的分数只留下评论,必须是一个答案。不管怎样,你能试试这样的东西吗:

    new_df = df.loc[:, 'residual'].groupby(df['ID']).std()
    
    

    我试着正常运行你的代码,但很明显,它没有完全发布,所以尝试有点困难我感谢你的反馈,我尝试了你的代码,它通过每个组ID创建了SD,但是我的问题是找到一个组中存在的每个数据点的SD,换句话说,我需要一个代码来计算我在每个日期时间和分组中的剩余SD。再次感谢你