计算Pandas每周的变化(用groupby)



我已经能够成功地计算出每周的变化,我的数据非常好。然而,我的数据包括我需要排序的数千个组。因此,我正在寻找一种比我目前实施方式更快/更有效的方法来计算这些每周的变化。

它目前的运行方式是,我有一个for循环,它每周对每个子集/store_ID进行更改。计算效果很好,但有超过10000个不同的项目要做,需要相当长的时间。有没有办法通过对我的"store_ID"列进行分组来做到这一点?我一直在玩.groupby。。。但不太确定如何使用它,因为它是一个groupby对象。

以下是我的代码及其工作方式:

我有一个名为df的数据帧,里面有我所有的信息。它已经被清理和排序了,所以每个store_ID都是按周升序排列的。为了简单起见,假设我只有以下列:

df[['store_ID', 'Week', 'Sales']]

所以。。。。

# Create list of each store
list_of_stores = list(df['store_ID'].unique())
# Create dataframe to dump the results into
results_df = pd.DataFrame()
# Iterate store-by-store to calculate the week to week values
for store in list_of_stores:
# Create a temporary dataframe to do the calculation for the store_ID
temp_df = pd.DataFrame()
temp_df = df[df['store_ID'] == store]
index_list = list(temp_df.index)
temp_df.index = temp_df['Week']
temp_df['Sales_change_1_week']= temp_df['Sales'] - 
temp_df['Sales'].shift(1, freq=Week())
temp_df.index = index_list
# Dump the temporary dataframe into a results dataframe
results_df = results_df.append(temp_df)

因此,在最后,我得到了所有store_ID每周的完整结果。我必须注意的是,有一些缺失的周,所以在这种情况下,我确实有无法计算与前一周相比变化的周的空值,我对此很满意。

所以我拿走了每个商店_ID:

  1. 创建一个临时数据帧,按"周"进行排序
  2. 我存储原始索引
  3. 然后按周重新索引(这样它就可以按周进行转换(
  4. 计算Sales每周的变化并放入新列
  5. 重新索引到原始索引
  6. 将其附加到结果数据帧
  7. 与下一个店铺重复_ID

我觉得有一种方法可以同时完成这一切,而不是单独处理每个store_ID,但似乎找不到方法。

这是我用来做类似事情的代码:

week_freq = 'W-TUE'
temp_df['Sales_change_1_week] = temp_df['Sales'].asfreq(week_freq).diff()

最新更新