(Pandas)处理缺少月份的月度数据

2024-06-17 11:44:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想能够计算销售预测使用过去12个月的数据价值的每一个产品我卖。你知道吗

我有一个产品名称,一个月的时间序列数据,以及那个月的购买数量。然而,在一些没有销售的月份,没有该月份的数据。你知道吗

我的数据帧如下所示:

2014-06  product1  100
2014-07  product1  50
2014-10  product1  120

但我希望它看起来像这样:

2014-06  product1  100
2014-07  product1  50
2014-08  product1  
2014-09  product1  
2014-10  product1  120

每个月都有一行,而不仅仅是有数据的月份。添加给定月份没有销售数据的行最有效的方法是什么?你知道吗


Tags: 数据方法数量产品时间序列价值月份
1条回答
网友
1楼 · 发布于 2024-06-17 11:44:38

您可以使用Dataframe.reindexto_period(),在构建一个包含缺失月份的新PeriodIndex之后使用Dataframe.reindex。首先,我将重新创建您的数据,将您的月份转换为Period的实例:

index = pd.to_datetime(['2014-06', '2014-07', '2014-10']).to_period('M')
data = pd.DataFrame({
        'name': 'product1',
        'count': [100, 50, 120]
    }, index=index)

现在,我们创建一个新索引,所有月份都在该范围内:

new_index = pd.date_range(
    start=index[0].to_timestamp(how='end'),
    end=index[-1].to_timestamp(how='end'),
    freq='M').to_period()

这看起来像:

>>> new_index
PeriodIndex(['2014-06', '2014-07', '2014-08', '2014-09', '2014-10'],
            dtype='int64', freq='M')

以便:

>>> res = data.reindex(new_index, method='backfill')
>>> res

         count      name
2014-06    100  product1
2014-07     50  product1
2014-08    120  product1
2014-09    120  product1
2014-10    120  product1

您会注意到namecount都被反写了,而您只希望name被反写。我们可以将新行的count设置为NaN,如下所示:

ix = new_index.difference(index)
res.loc[ix, 'count'] = None

以便:

>>> res

         count      name
2014-06    100  product1
2014-07     50  product1
2014-08    NaN  product1
2014-09    NaN  product1
2014-10    120  product1

相关问题 更多 >