我正在尝试实现一个滚动平均值,每当在标签为'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'在搜索了Dask文档之后,我还没有找到我想要的东西的实现。
有人能建议以Dask兼容的方式实现这个算法吗?
谢谢您:)
从那时起,我发现了以下代码片段:
df1 = ddf.groupby('cumsum')['x'].apply(lambda x: x.rolling(2).mean(), meta=('x', 'f8')).compute()下面是一个经过改编的玩具示例:
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这具有正确的功能,但是索引的顺序现在是不正确的。或者,如果一个人知道如何保持索引的顺序,那将是一个合适的解决方案。
发布于 2019-03-27 05:00:49
您可能希望使用重叠或_cum_agg方法构建自己的滚动操作(不幸的是,cum_agg没有很好的文档说明)。
https://stackoverflow.com/questions/55290216
复制相似问题