【发布时间】:2014-12-11 11:00:06
【问题描述】:
我有一个包含许多观察的数据框:
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
我想通过colour 和date 对数据框进行排序,然后尝试重新索引它。
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,我是熊猫新手。我认为初始数据框实际上根本没有索引。我已经对它进行了排序,但没有设置任何索引。
-
但我的意思是,您在
ts = test_df.reindex(index)行中使用了一个名为index的变量。那到底是什么? -
抱歉,我已经编辑了最初的问题,但缺少那行代码。理想情况下,我会让熊猫自动找到开始和结束日期。就像数据框中的日期越来越小。我刚刚看到命令
test_df.resample('D')是为了做到这一点,但我认为我应该事先按'date'索引test_df,我正在努力解决这个问题。
标签: python pandas date-range reindex