熊猫滚动汇总功能列表。 ValueError:无结果

时间:2019-09-02 14:00:53

标签: python pandas aggregate rolling-computation

滚动后的聚合方法不适用于功能列表。

此代码引发Valueerror。

df = pd.DataFrame({'col1':range(3), 'date':pd.date_range('2018-01-01', '2018-01-03')})
df.rolling('6D', min_periods=1, on='date', closed='left').agg([sum])

但是此代码仅适用于单个功能。

df.rolling('6D', min_periods=1, on='date', closed='left').agg(sum)

错误文字:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-389-91b03860c0e6> in <module>
----> 1 df.rolling('6D', min_periods=1, on='date', closed='left').agg([sum])

~/anaconda3/lib/python3.7/site-packages/pandas/core/window.py in aggregate(self, arg, *args, **kwargs)
   1683     @Appender(_shared_docs['aggregate'])
   1684     def aggregate(self, arg, *args, **kwargs):
-> 1685         return super(Rolling, self).aggregate(arg, *args, **kwargs)
   1686 
   1687     agg = aggregate

~/anaconda3/lib/python3.7/site-packages/pandas/core/window.py in aggregate(self, arg, *args, **kwargs)
    310 
    311     def aggregate(self, arg, *args, **kwargs):
--> 312         result, how = self._aggregate(arg, *args, **kwargs)
    313         if result is None:
    314             return self.apply(arg, raw=False, args=args, kwargs=kwargs)

~/anaconda3/lib/python3.7/site-packages/pandas/core/base.py in _aggregate(self, arg, *args, **kwargs)
    557             return self._aggregate_multiple_funcs(arg,
    558                                                   _level=_level,
--> 559                                                   _axis=_axis), None
    560         else:
    561             result = None

~/anaconda3/lib/python3.7/site-packages/pandas/core/base.py in _aggregate_multiple_funcs(self, arg, _level, _axis)
    615         # if we are empty
    616         if not len(results):
--> 617             raise ValueError("no results")
    618 
    619         try:

ValueError: no results

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。我不知道为什么,但是在这种情况下,我们需要使用日期列作为索引。

df.set_index('date').rolling('6D', min_periods=1, closed='left').agg(['sum','max'])

结果

           col1     
            sum  max
date                
2018-01-01  NaN  0.0
2018-01-02  0.0  1.0
2018-01-03  1.0  2.0