【发布时间】:2016-06-23 04:08:26
【问题描述】:
在回答this stackoverflow question 时,我发现在重新索引数据帧时使用填充方法时出现了一些有趣的行为。
pandas 中的 old bug report 表示 df.reindex(newIndex,method='ffill') 应该等同于 df.reindex(newIndex).ffill(),但这不是我所看到的行为
这是一个说明行为的代码 sn-p
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 的参数调用时会失败。
【问题讨论】: