代码之家  ›  专栏  ›  技术社区  ›  Steve Lorimer

熊猫统计函数和Boost::Accumulator之间的差异

  •  3
  • Steve Lorimer  · 技术社区  · 7 年前

    我得到了不同的统计计算结果 pandas boost::accumulators 我不确定为什么。

    下面我有一个简单的例子,用熊猫计算一些收益的均值和方差。

    import pandas
    
    vals = [ 1, 1, 2, 1, 3, 2, 3, 4, 6, 3, 2, 1 ]
    rets = pandas.Series(vals).pct_change()
    
    print(f'count:    {len(rets)}')
    print(f'mean:     {rets.mean()}')
    print(f'variance: {rets.var()}')
    

    其结果是:

    count:    12
    mean:     0.19696969696969696
    variance: 0.6156565656565657
    

    我正在做C++中的等价用法 增压::蓄能器 用于统计计算

    #include <iostream>
    #include <iomanip>
    #include <cmath>
    #include <boost/accumulators/accumulators.hpp>
    #include <boost/accumulators/statistics/stats.hpp>
    #include <boost/accumulators/statistics/count.hpp>
    #include <boost/accumulators/statistics/mean.hpp>
    #include <boost/accumulators/statistics/variance.hpp>
    
    namespace acc = boost::accumulators;
    
    int main()
    {
        acc::accumulator_set<double, acc::stats<acc::tag::count,
                                                acc::tag::mean,
                                                acc::tag::variance>> stats;
    
        double prev = NAN;
        for (double val : { 1, 1, 2, 1, 3, 2, 3, 4, 6, 3, 2, 1 })
        {
            const double ret = (val - prev) / prev;
    
            stats(std::isnan(ret) ? 0 : ret);
    
            prev = val;
        }
    
        std::cout << std::setprecision(16)
                  << "count:    " << acc::count(stats)    << '\n'
                  << "mean:     " << acc::mean(stats)     << '\n'
                  << "variance: " << acc::variance(stats) << '\n';
    
        return 0;
    }
    

    其结果是:

    count:    12
    mean:     0.1805555555555556
    variance: 0.5160108024691359
    
    • 为什么大熊猫和Boost::Accumulators之间的平均值和方差不同?
    • 我需要做什么才能从Boost::Accumulators得到熊猫的结果?
    1 回复  |  直到 7 年前
        1
  •  1
  •   BENY    7 年前

    在熊猫中,它会移除 nan 当你这样做的时候列 mean 如果我们填满 作为0,输出是相同的,因为你 pct_change ,第一项应为NaN

    rets.mean()
    Out[67]: 0.19696969696969696
    
    rets.fillna(0).mean()
    Out[69]: 0.18055555555555555
    

    关于 var 使自由度为0

    rets.fillna(0).var(ddof=0)
    Out[86]: 0.5160108024691358