建立预测熊猫数据框架

时间:2020-09-11 16:27:41

标签: python pandas

我在Pandas中有一个DataFrame,其中包含如下所示的预测销售数据:

   | Date  | ProductID | Forecasted_Date | Sales |
---|-------|-----------|-----------------|-------|
 0 | 1_Jan | 1         | 2_Jan           | 10    |
 1 | 1_Jan | 2         | 3_Jan           | 3     |
 2 | 1_Jan | 1         | 2_Jan           | 7     |
 3 | ...   |           |                 |       |
 4 | 2_Jan | 1         | 3_Jan           | 7     |

在每个日期和每个ProductId上,预测销售会在最前面1到20天(预测日期)之间进行。

我想创建一个新的DataFrame,并以“ [Date,ProductID]”作为多索引,并包含以下列:

| IND_Date | IND_ProductID | F1 | F2   | ... | F20 |
|----------|---------------|----|------|-----|-----|
| 1_Jan    | 1             | 10 | 3    |     |     |
| 1_Jan    | 2             | 7  | etc. |     |     |
| ...      |               |    |      |     |     |
| 2_Jan    | 1             | 7  |      |     |     |

其中的列表示进行预测的天数。 (即,对于Date = 1_Jan,F1 = Sales on 2_Jan)。

在Pandas中构建它的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

我知道了。

如果df是我的基本数据框...

  1. 假设Date和Forecasted_Date采用Datetime格式,以天为单位查找差异:
df['difference'] = (df['Forecasted_Date'] - df['Date']) / pd.Timedelta(1,'D'))
  1. 转换为必需的“ f_”格式:
df['forecast_day'] = 'f_' + df['difference'].astype('int').astype('str')
  1. 创建数据透视表
df_forecast = pd.pivot_table(data=df, values="Sales", index=["Date", "Product_ID"], columns="forecast_day", aggfunc="sum")

完成!