Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算销售滚动(滞后和领先)差异的最佳方法是什么?_Python_Python 3.x_Performance_Iteration_Rolling Computation - Fatal编程技术网

Python 计算销售滚动(滞后和领先)差异的最佳方法是什么?

Python 计算销售滚动(滞后和领先)差异的最佳方法是什么?,python,python-3.x,performance,iteration,rolling-computation,Python,Python 3.x,Performance,Iteration,Rolling Computation,我希望在我的数据集中添加一两个字段,表示上周到本周以及本周到下周的销售额差异 我的数据集大约有450万行,因此我正在寻找一种有效的方法来实现这一点,目前我正在进行大量的迭代和for循环,我很确定我的做法是错误的。但我正在尝试编写可在其他数据集上重用的代码,在某些情况下,每周的销售额可能为空或没有变化(因此没有记录) 数据集如下所示: Store Item WeekID WeeklySales 1 1567 34 100.00 2 2765 34

我希望在我的数据集中添加一两个字段,表示上周到本周以及本周到下周的销售额差异

我的数据集大约有450万行,因此我正在寻找一种有效的方法来实现这一点,目前我正在进行大量的迭代和for循环,我很确定我的做法是错误的。但我正在尝试编写可在其他数据集上重用的代码,在某些情况下,每周的销售额可能为空或没有变化(因此没有记录)

数据集如下所示:

Store  Item  WeekID  WeeklySales
1      1567   34      100.00
2      2765   34      86.00
3      1163   34      200.00
1      1567   35      160.00
.      .
.      . 
.      .
我每周都有自己的字典,然后每个商店都会在一本字典内为那一周的销售做准备。因此,我可以使用一周作为一个关键,然后在一周内,我访问商店的商品销售字典

weekly_sales_dict = {}
for i in df['WeekID'].unique():
    store_items_dict = {}
    subset = df[df['WeekID'] == i]
    subset = subset.groupby(['Store', 'Item']).agg({'WeeklySales':'sum'}).reset_index()
    for j in subset['Store'].unique():
        storeset = subset[subset['Store'] == j]
        store_items_dict.update({str(j): storeset})
    weekly_sales_dict.update({ str(i) : store_items_dict})
然后,我在每周销售目录中重复每一周,并将其中的每个商店/商品与后面的一周进行比较(我计划在下周也这样做)。我创建的'lag_list'可以按周、存储区和项目编制索引,因此我打算迭代并将值添加到我的df中,作为一个新的lag列,但我觉得我想得太多了

count = 0 
key_list = list(df['WeekID'].unique())
lag_list = []
for k,v in weekly_sales_dict.items():
    if count != 0 and count != len(df['WeekID'].unique())-1:
        prev_wk = weekly_sales_dict[str(key_list[(count - 1)])]
        current_wk = weekly_sales_dict[str(key_list[count])
        for i in df['Store'].unique():
            prev_df = prev_wk[str(i)]
            current_df = current_wk[str(i)]
            for j in df['Item'].unique():
                print('in j')
                if j in list(current_df['Item'].unique()) and j in list(prev_df['Item'].unique()):
                    item_lag = current_df[current_df['Item'] == int(j)]['WeeklySales'].values - prev_df[prev_df['Item'] == int(j)]['WeeklySales'].values
                    df[df['Item'] == j][df['Store'] == i ][df['WeekID'] == key_list[count]]['lag'] = item_lag[0]
                    lag_list.append((str(i),str(j),item_lag[0]))
                elif j in list(current_df['Item'].unique()):
                    item_lag = current_df[current_df['Item'] == int(j)]['WeeklySales'].values
                    lag_list.append((str(i),str(j),item_lag[0]))
                else:
                    pass
        count += 1
    else:            
        count += 1
使用
pd.diff()
解决了问题。我按周对所有行进行排序,然后通过对存储、项目和周进行分组,创建了一个具有多索引的子集。最后,我使用了周期为1的pd.diff(),最后得到了本周与前一周的销售差异

df = df.sort_values(by = 'WeekID')

subset = df.groupby(['Store', 'Items', 'WeekID']).agg({''WeeklySales'':'sum'})
subset['lag']  = subset[['WeeklySales']].diff(1)

你看过
pd.DataFrame.rolling()
了吗?我看过了,但示例似乎集中在日期上,以确定周期,因为我使用的是周ID,我想我可能需要走不同的路线。我可以在大约4小时内完成解决方案,如果到时候没有答案,我忘了!你还卡住了吗?别担心!我在这方面没有取得任何进展。。。。今天我打算尝试pd.rolling(),但是这些例子对我来说没有太大意义。