在回答 这个stackoverflow问题 时,我发现在重新索引数据框时使用fill方法会出现一些有趣的行为。
pandas中的 旧bug报告 表示df.reindex(newIndex,method='ffill')
应该等同于df.reindex(newIndex).ffill()
,但我目睹的情况并非如此。
下面是一个代码片段,用于说明这种行为
df = pd.DataFrame({'values': 2}, index=pd.DatetimeIndex(['2016-06-02', '2016-05-04', '2016-06-03']))
newIndex = pd.DatetimeIndex(['2016-05-04', '2016-06-01', '2016-06-02', '2016-06-03', '2016-06-05'])
print(df.reindex(newIndex).ffill())
print(df.reindex(newIndex, method='ffill'))
第一个打印语句按预期工作。第二个引发错误。
ValueError: index must be monotonic increasing or decreasing
这里发生了什么?
编辑:请注意,示例df
有意具有非单调索引。问题涉及在df.reindex(newIndex, method='ffil')
中的操作顺序。我的期望是,它应该按照错误报告所说的方式工作- 首先重新索引新的索引,然后填充。
正如您所看到的,newIndex.is_monotonic
为True
,并且在单独调用填充时可以工作,但在作为reindex
参数调用时失败。