按照新日期范围重新索引数据框。

10

我有一个包含多个观测值的数据框:

date         colour     orders
2014-10-20   red        7
2014-10-21   red        10
2014-10-20   yellow     3

我想重新索引数据框并标准化日期。

date         colour     orders
2014-10-20   red        7
2014-10-21   red        10
2014-10-22   red        NaN
2014-10-20   yellow     3
2014-10-21   yellow     NaN
2014-10-22   yellow     NaN

我想按照 colourdate 对数据框进行排序,然后尝试重新索引。

index = pd.date_range('20/10/2014', '22/10/2014')
test_df = df.sort(['colour', 'date'], ascending=(True, True))
ts = test_df.reindex(index)
ts

但它返回一个具有正确索引但所有NaN值的新数据帧。

date         colour     orders
2014-10-20   NaN        NaN
2014-10-21   NaN        NaN
2014-10-22   NaN        NaN

在你的例子中,index是什么? - joris
嗨Joris,我是pandas的新手。我认为最初的数据框实际上根本没有索引。我已经对其进行了排序,但没有设置任何索引。 - Gianluca
但是我的意思是,在ts = test_df.reindex(index)这一行中,您使用了一个名为“index”的变量。那具体是什么呢? - joris
抱歉,我已经编辑了初始问题,缺少一行代码。理想情况下,我希望pandas可以自动找到开始和结束日期...就像数据框中的较小日期和较大日期一样。我刚刚看到命令test_df.resample('D')是用来做这个的,但我认为我应该先按“日期”对test_df进行索引,这是我正在努力解决的问题。 - Gianluca
1个回答

18

从您的示例数据框开始:

In [51]: df
Out[51]:
        date  colour  orders
0 2014-10-20     red       7
1 2014-10-21     red      10
2 2014-10-20  yellow       3

如果您想在“日期”和“颜色”上重新索引,一种可能的方法是将它们都设为索引(多重索引):

如果您想在“日期”和“颜色”上重新索引,一种可能的方法是将它们都设为索引(多重索引):

In [52]: df = df.set_index(['date', 'colour'])

In [53]: df
Out[53]:
                   orders
date       colour
2014-10-20 red          7
2014-10-21 red         10
2014-10-20 yellow       3

在你构建所需的索引之后,你现在可以重新索引这个数据框:

In [54]: index = pd.date_range('20/10/2014', '22/10/2014')

In [55]: multi_index = pd.MultiIndex.from_product([index, ['red', 'yellow']])

In [56]: df.reindex(multi_index)
Out[56]:
                   orders
2014-10-20 red          7
           yellow       3
2014-10-21 red         10
           yellow     NaN
2014-10-22 red        NaN
           yellow     NaN
为了获得与您的示例输出相同的输出结果,在第二级中应按索引排序(level=1,因为它是基于0的):
In [60]: df2 = df.reindex(multi_index)

In [64]: df2.sortlevel(level=1)
Out[64]:
                   orders
2014-10-20 red          7
2014-10-21 red         10
2014-10-22 red        NaN
2014-10-20 yellow       3
2014-10-21 yellow     NaN
2014-10-22 yellow     NaN
可能自动生成多层索引的一种方式是(使用您原始的数据框):
pd.MultiIndex.from_product([pd.date_range(df['date'].min(), df['date'].max(), freq='D'), 
                            df['colour'].unique()])

另一种方法是对每组颜色使用 resample


In [77]: df = df.set_index('date')

In [78]: df.groupby('colour').resample('D')

这样更简单,但是它并不能给出每种颜色的完整日期范围,只能提供该颜色组可用的日期范围。


假设我有成千上万个产品(公平起见,我不只有一个列,而是有一个用于类别、各种子类别等的列),我该如何更改代码的这一部分 multi_index = pd.MultiIndex.from_product([index, ['red', 'yellow']]) - Gianluca
请参考我的“一种可能的自动生成多级索引的方法…”,当colour列中有很多值时,可以使用该方法。 - joris
@Gianluca 这个解决了你的问题吗?还是还有问题? - joris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接