将ewm功能应用于Pandas groupby

时间:2020-10-18 07:55:22

标签: python pandas pandas-groupby

我有这个DataFrame

day

我想按val分组,并将ddd.groupby(['day']).mean() val day m 8 t 6 ewm汇总

如果我进行groupby并表示我明白了

ddd.groupby(['day']).ewm(com=1.0).mean()

如果我尝试的话,现在也一样

AttributeError: 'DataFrameGroupBy' object has no attribute 'ewm'

我收到错误 val day m 4.733333 t 8.133333

我的预期输出看起来像这样

    /**
     * Calculate the value of the metric.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @return mixed
     */
    public function calculate(NovaRequest $request)
    {
        $settlement  = new \App\Models\VmsSettlement\Settlement;

        $twoDaysAgoSum      = $settlement->where('status', 'PENDING')->where('settlement_date', Carbon::today()->subDays(2)->toDateString())->sum('amount');
        $yesterdaySum       = $settlement->where('status', 'PENDING')->where('settlement_date', Carbon::today()->subDay()->toDateString())->sum('amount');
        $todaySum           = $settlement->where('status', 'PENDING')->where('settlement_date', Carbon::today()->toDateString())->sum('amount');
        $tomorrowSum        = $settlement->where('status', 'PENDING')->where('settlement_date', Carbon::today()->addDay()->toDateString())->sum('amount');
        $twoDaysLaterSum    = $settlement->where('status', 'PENDING')->where('settlement_date', Carbon::today()->addDays(2)->toDateString())->sum('amount');

        return (new TrendResult)->trend([
             Carbon::today()->subDays(2)->toDateString() . ' (2 days ago)'   => $twoDaysAgoSum,
             Carbon::today()->subDay()->toDateString() . ' (Yesterday)'            => $yesterdaySum,
             Carbon::today()->toDateString() . ' (Today)'                          => $todaySum,
             Carbon::today()->addDay()->toDateString() . ' (Tomorrow)'             => $tomorrowSum,
             Carbon::today()->addDays(2)->toDateString() . ' (2 days later)' => $twoDaysLaterSum,
        ])->format('0,0');
    }

    /**
     * Get the ranges available for the metric.
     *
     * @return array
     */
    public function ranges()
    {
        return [
            //30 => '30 Days',
            //60 => '60 Days',
            //90 => '90 Days',
        ];
    }

1 个答案:

答案 0 :(得分:2)

并非所有dataframeseries函数都为groupby对象实现。但是您可以使用apply来获得预期的结果

ddd.groupby(['day']).apply(lambda x: x.ewm(com=1.0).mean().iloc[-1])

出局:

          val
day          
m    4.733333
t    8.133333