熊猫石斑鱼“累积”总和()

时间:2021-05-18 14:48:03

标签: python pandas numpy pandas-groupby cumsum

我正在尝试计算接下来 4 周的累计总数。

这是我的数据框示例

d = {'account': [10, 10, 10, 10, 10, 10, 10, 10],
     'volume': [25, 60, 40, 100, 50, 100, 40, 50]}
df = pd.DataFrame(d)
df['week_starting'] = pd.date_range('05/02/2021',
                                    periods=8,
                                    freq='W')
df['volume_next_4_weeks'] = [225, 250, 290, 290, 240, 190, 90, 50]
df['volume_next_4_weeks_cumulative'] = ['(25+60+40+100)', '(60+40+100+50)', '(40+100+50+100)', '(100+50+100+40)', '(50+100+40+50)', '(100+40+50)', '(40+50)', '(50)']
df.head(10)

dataframe_table_view

我想找到一种方法来计算 pd.Grouper freq = 4W 的累积量。

2 个答案:

答案 0 :(得分:0)

这应该有效:

df['volume_next_4_weeks']  = [sum(df['volume'][i:i+4]) for i in range(len(df))]

对于将加法显示为 string 的另一列,我使用上述相同的逻辑将值存储在列表中,但不应用 sum,然后将列表元素连接为 string

df['volume_next_4_weeks_cumulative'] = [df['volume'][i:i+4].to_list() for i in range(len(df))]
df['volume_next_4_weeks_cumulative'] = df['volume_next_4_weeks_cumulative'].apply(lambda row: ' + '.join(str(x) for x in row))

现在,正如您所提到的,您有多个不同的帐户,并且希望为所有帐户分别执行此操作,请创建一个自定义函数,然后使用 groupbyapply 创建列:

def create_mov_cols(df):
    df['volume_next_4_weeks']  = [sum(df['volume'][i:i+4]) for i in range(len(df))]
    df['volume_next_4_weeks_cumulative'] = [df['volume'][i:i+4].to_list() for i in range(len(df))]
    df['volume_next_4_weeks_cumulative'] = df['volume_next_4_weeks_cumulative'].apply(lambda row: ' + '.join(str(x) for x in row))
    return df

将函数应用到DataFrame:

df = df.groupby(['account']).apply(create_mov_cols)

答案 1 :(得分:0)

df['volume_next_4_weeks'] = df[['week_starting', 'volume']][::-1].rolling(window='28D', on='week_starting').sum()[::-1]['volume']
使用

28D 代替 4W,因为后者不是固定频率。