【问题标题】:How to set rolling window size by size of each group?如何按每个组的大小设置滚动窗口大小?
【发布时间】:2020-02-11 12:40:11
【问题描述】:

我有一个如下的数据框:

>df

ID    Value
---------------
1       1.0
1       2.0
1       3.0
1       4.0
2       6.0
2       7.0
2       8.0
3       2.0

我想在每个组的最后一个int(group size /2) 记录的“值”字段上计算min/max/sum/mean/var,而不是固定记录数。

  • 对于 ID =1,将 min/max/sum/mean/var 应用于最后 4/2=2 条记录的“值”字段
  • 对于 ID =2,将 min/max/sum/mean/var 应用于最后 3/2=1 条记录的“值”字段。
  • 对于 ID =3,将 min/max/sum/mean/var 应用于最后 1 条记录的“值”字段,因为它在组中只有一条记录。

所以输出应该是

             Value
ID    min   max  sum  mean  var
----------------------------------
1     3.0   4.0  7.0  3.5    0.5 # the last 4/2 rows for group with ID =1
2     7.0   7.0  7.0  7.0    0.5 # the last 3/2 rows for group with ID =2
3     2.0   2.0  2.0  2.0    Nan # the last 1 rows for group with ID =3

我正在考虑使用rolling 函数,如下所示:

df_group=df.groupby('ID')
           .apply(lambda x: x \
                           .sort_values(by=['ID'])
                           .rolling(window=int(x.size/2),min_periods=1)
                           .agg({'Value':['min','max','sum','mean','var']})
                           .tail(1)
                  )

但结果却如下

                Value
        min max sum    mean  var
ID                      
------------------------------------------------
1   3   1.0 4.0 10.0    2.5 1.666667
2   6   6.0 8.0 21.0    7.0 1.000000
3   7   2.0 2.0 2.0     2.0 NaN

似乎 x.size 根本不起作用。

有没有办法根据组大小设置滚动大小?

【问题讨论】:

  • 嗨,您能分享一下您尝试过的操作以及预期的结果(数据框或其他)吗?
  • 我已经用我所做的和预期的输出更新了这个问题,有什么提示吗?
  • 不知道为什么需要翻转数据框,请参阅stackoverflow.com/a/60223067/3941704 以获得可能的解决方案

标签: python window grouping rolling-computation


【解决方案1】:

一个可能的解决方案:

import pandas as pd
df = pd.DataFrame(dict(ID=[1,1,1,1,2,2,2,3],
                      Value=[1,2,3,4,6,7,8,2]))

print(df)
##
   ID  Value
0   1      1
1   1      2
2   1      3
3   1      4
4   2      6
5   2      7
6   2      8
7   3      2

如下循环组

#Object to store the result
stats = []

#Group over ID
for ID, Values in df.groupby('ID'):
    # tail : to get last n values, with n max between 1 and group length / 2
    # describe : to get the statistics
    _stat = Values.tail(max(1,int(len(Values)/2)))['Value'].describe()
    #Add group ID to the result
    _stat.loc['ID'] = ID
    #Store the result
    stats.append(_stat)

#Create the new dataframe
pd.DataFrame(stats).set_index('ID')

结果

     count  mean       std  min   25%  50%   75%  max
ID                                                   
1.0    2.0   3.5  0.707107  3.0  3.25  3.5  3.75  4.0
2.0    1.0   8.0       NaN  8.0  8.00  8.0  8.00  8.0
3.0    1.0   2.0       NaN  2.0  2.00  2.0  2.00  2.0

链接:

【讨论】:

    猜你喜欢
    • 2023-04-11
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多