猿问

使用条件过滤器对动态选择的列进行分组操作

我有一个数据框如下:


   Date        Group   Value   Duration

2018-01-01      A      20       30

2018-02-01      A      10       60

2018-01-01      B      15      180

2018-02-01      B      30      210

2018-03-01      B      25      238 

2018-01-01      C      10      235

2018-02-01      C      15      130

我想group_by动态使用,即不希望键入group_by要应用的列名。具体来说,我想计算mean每个组最近两个月的数据。

正如我们所看到的,并非每个组的数据都出现在上述数据框中的所有日期。所以任务如下:

  1. 添加一个基于日期的虚拟行,以防与Date = 2018-03-01每个组不存在的数据相关(例如为 A 和 C 添加行)。

  2. group_by使用最近两个月的Value和执行计算均值Duration

所以我的做法如下:

对于任务 1:

 s = pd.MultiIndex.from_product(df['Date'].unique(),df['Group'].unique()],names=['Date','Group'])

 df = df.set_index(['Date','Group']).reindex(s).reset_index().sort_values(['Group','Date']).ffill(axis=0) 

我们可以有更好的方法来完成“添加行”任务吗?可在此处找到参考。


对于任务 2:


def cond_grp_by(df,grp_by:str,cols_list:list,*args):

    df_grp = df.groupby(grp_by)[cols_list].transform(lambda x : x.tail(2).mean())

    return df_grp

df_cols = df.columns.tolist()

df = cond_grp_by(dealer_f_filt,'Group',df_cols)

可以在此处找到上述方法的参考。


上面的代码正在抛出IndexError : Column(s) ['index','Group','Date','Value','Duration'] already selected


预期的输出是


Group    Value    Duration

  A       10         60 <---------   Since a row is added for 2018-03-01 with 

  B       27.5      224              same value as 2018-02-01,we are 

  C       15        130 <---------   computing mean for last two values


Smart猫小萌
浏览 112回答 1
1回答

30秒到达战场

如果需要由聚合值填充的输出,GroupBy.agg请改用:transformdef cond_grp_by(df,grp_by:str,cols_list:list,*args):&nbsp; &nbsp; return df.groupby(grp_by)[cols_list].agg(lambda x : x.tail(2).mean()).reset_index()df = cond_grp_by(df,'Group',df_cols)print (df)&nbsp; Group&nbsp; Value&nbsp; Duration0&nbsp; &nbsp; &nbsp;A&nbsp; &nbsp;10.0&nbsp; &nbsp; &nbsp; 60.01&nbsp; &nbsp; &nbsp;B&nbsp; &nbsp;27.5&nbsp; &nbsp; &nbsp;224.02&nbsp; &nbsp; &nbsp;C&nbsp; &nbsp;15.0&nbsp; &nbsp; &nbsp;130.0如果需要每个组的最后一个值,请使用GroupBy.last:def cond_grp_by(df,grp_by:str,cols_list:list,*args):&nbsp; &nbsp; return df.groupby(grp_by)[cols_list].last().reset_index()df = cond_grp_by(df,'Group',df_cols)
随时随地看视频慕课网APP

相关分类

Python
我要回答