Skip to main content
 首页 » 编程设计

python之ValueError: index必须是单调递增或单调递减的,同时包含index,column,ffill

2025年05月04日7java哥

我使用的 pandas 版本是'0.20.1',python 3

虽然有两个问题: question1 , question2 被问到同样的错误,而我发现这两个问题和我的情况不一样。

数据来源于《数据分析用Python》一书,第123-124页。 当我运行以下代码时,

frame = DataFrame(np.arange(9).reshape((3, 3)), index=['a', 'c', 'd'], 
                  columns=['Ohio', 'Texas', 'California']) 
states = ['Texas', 'Utah', 'California'] 
frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill',columns=states) 

报错

ValueError: index must be monotonic increasing or decreasing 

虽然我尝试了以下两个表达式,但它们运行成功:

frame.reindex(index=['a', 'b', 'c', 'd'], columns=states) 

或

frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill') 

************************更新***************

我试过这段代码,

frame3=frame.reindex(index=['a', 'b', 'c', 'd'], method='ffill').reindex(columns=states) 

然后它返回与书本相同的结果。

Out[92]: 
Texas Utah California 
a 1 NaN 2 
b 1 NaN 2 
c 4 NaN 5 
d 7 NaN 8 

请您参考如下方法:

因为列也被重新索引,它们不是单调增加或减少的。