Dask 达斯克的分组滚动方案

Dask 达斯克的分组滚动方案,dask,Dask,我正在尝试实现一个滚动平均值,每当在标记为“a”的列中遇到“1”时,该值就会重置 例如,以下功能在Pandas中起作用 import pandas as pd x = pd.DataFrame([[0,2,3], [0,5,6], [0,8,9], [1,8,9],[0,8,9],[0,8,9], [0,3,5], [1,8,9],[0,8,9],[0,8,9], [0,3,5]]) x.columns = ['A', 'B', 'C'] x['avg'] = x.groupby(x['A'

我正在尝试实现一个滚动平均值,每当在标记为“a”的列中遇到“1”时,该值就会重置

例如,以下功能在Pandas中起作用

import pandas as pd

x = pd.DataFrame([[0,2,3], [0,5,6], [0,8,9], [1,8,9],[0,8,9],[0,8,9], [0,3,5], [1,8,9],[0,8,9],[0,8,9], [0,3,5]])
x.columns = ['A', 'B', 'C']

x['avg'] = x.groupby(x['A'].cumsum())['B'].rolling(2).mean().values
如果我在Dask中尝试一个类似的代码,我会得到以下结果:

import pandas as pd
import dask

x = pd.DataFrame([[0,2,3], [0,5,6], [0,8,9], [1,8,9],[0,8,9],[0,8,9], [0,3,5], [1,8,9],[0,8,9],[0,8,9], [0,3,5]])
x.columns = ['A', 'B', 'C']

x = dask.dataframe.from_pandas(x, npartitions=3)

x['avg'] = x.groupby(x['A'].cumsum())['B'].rolling(2).mean().values
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-189-b6cd808da8b1> in <module>()
      7 x = dask.dataframe.from_pandas(x, npartitions=3)
      8 
----> 9 x['avg'] = x.groupby(x['A'].cumsum())['B'].rolling(2).mean().values
     10 x

AttributeError: 'SeriesGroupBy' object has no attribute 'rolling'

以下是一个经过改编的玩具示例:

import pandas as pd
import dask.dataframe as dd

x = pd.DataFrame([[1,2,3], [2,3,4], [4,5,6], [2,3,4], [4,5,6],  [4,5,6], [2,3,4]])
x['bool'] = [0,0,0,1,0,1,0]
x.columns = ['a', 'b', 'x', 'bool']

ddf = dd.from_pandas(x, npartitions=4)
ddf['cumsum'] = ddf['bool'].cumsum()

df1 = ddf.groupby('cumsum')['x'].apply(lambda x: x.rolling(2).mean(), meta=('x', 'f8')).compute()
df1

这具有正确的功能,但索引的顺序现在不正确。或者,如果知道如何保持索引的顺序,那将是一个合适的解决方案。

您可能希望使用或
\u cum\u agg
方法构建自己的滚动操作(遗憾的是cum\u agg没有很好的文档)

import pandas as pd
import dask.dataframe as dd

x = pd.DataFrame([[1,2,3], [2,3,4], [4,5,6], [2,3,4], [4,5,6],  [4,5,6], [2,3,4]])
x['bool'] = [0,0,0,1,0,1,0]
x.columns = ['a', 'b', 'x', 'bool']

ddf = dd.from_pandas(x, npartitions=4)
ddf['cumsum'] = ddf['bool'].cumsum()

df1 = ddf.groupby('cumsum')['x'].apply(lambda x: x.rolling(2).mean(), meta=('x', 'f8')).compute()
df1