gpt4 book ai didi

python - Pandas 重建索引并填充缺失值 : "Index must be monotonic"

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:06 27 4
gpt4 key购买 nike

在回答this stackoverflow question ,我在重新索引数据帧时使用填充方法时发现了一些有趣的行为。

old bug report在 Pandas 中说 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_monotonicTrue ,填充在单独调用时有效,但在作为 reindex 的参数调用时失败。 .

最佳答案

reindex 的某些元素需要对传入索引进行排序。我推断当 method 被传递时,它无法对传入索引进行预排序,随后失败。我是基于这个有效的事实得出这个结论的:

print df.sort_index().reindex(newIndex.sort_values(), method='ffill')

关于python - Pandas 重建索引并填充缺失值 : "Index must be monotonic",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37982170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com