微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

熊猫石斑鱼“累积”总和

如何解决熊猫石斑鱼“累积”总和

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

这是我的数据框示例

d = {'account': [10,10,10],'volume': [25,60,40,100,50,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,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 的累积量。

解决方法

这应该有效:

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)
,
df['volume_next_4_weeks'] = df[['week_starting','volume']][::-1].rolling(window='28D',on='week_starting').sum()[::-1]['volume']
使用

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。