Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.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_Pandas - Fatal编程技术网

Python 建筑预测数据框架

Python 建筑预测数据框架,python,pandas,Python,Pandas,我在Pandas中有一个数据框,其中包含预测的销售数据,如下所示: | Date | ProductID | Forecasted_Date | Sales | ---|-------|-----------|-----------------|-------| 0 | 1_Jan | 1 | 2_Jan | 10 | 1 | 1_Jan | 2 | 3_Jan | 3 | 2 | 1_Jan |

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

   | 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天之间(预测的_日期)

我想创建一个新的数据框,由“[Date,ProductID]”和以下列组成多索引:

| IND_Date | IND_ProductID | F1 | F2   | ... | F20 |
|----------|---------------|----|------|-----|-----|
| 1_Jan    | 1             | 10 | 3    |     |     |
| 1_Jan    | 2             | 7  | etc. |     |     |
| ...      |               |    |      |     |     |
| 2_Jan    | 1             | 7  |      |     |     |
其中,列表示预测的提前天数。(即,日期=1月1日,F1=1月2日的销售额)

在熊猫身上构造这个的最好方法是什么?

我想出来了

如果
df
是我的基本数据帧

  • 以天为单位查找差异,假设日期和预测的_日期为Datetime格式:
  • 转换为所需的“f_”格式:
  • 创建数据透视表
  • 完成了

    df['difference'] = (df['Forecasted_Date'] - df['Date']) / pd.Timedelta(1,'D'))
    
    df['forecast_day'] = 'f_' + df['difference'].astype('int').astype('str')
    
    df_forecast = pd.pivot_table(data=df, values="Sales", index=["Date", "Product_ID"], columns="forecast_day", aggfunc="sum")