ValueError:index必须是单调递增或递减

问题描述 投票:1回答:3

ser3 = Series(['USA','Mexico','Canada'],index = ['0','5','10'])

这里ranger = range(15)

我在iPython中使用Forward fill时遇到错误

ser3.reindex(ranger,method = 'ffill')

/Users/varun/anaconda/lib/python2.7/site-packages/pandas/core/index.pyc in _searchsorted_monotonic(self, label, side)
   2395             return len(self) - pos
   2396 
-> 2397         raise ValueError('index must be monotonic increasing or decreasing')
   2398 
   2399     def get_slice_bound(self, label, side, kind):

ValueError: index must be monotonic increasing or decreasing
numpy pandas ipython ipython-notebook
3个回答
3
投票

正如大卫所说,这是由于索引是一个字符串。但是,为什么你得到“索引不单调错误”,答案是 - 为了重新索引方法,你的索引必须是有序/单调/递增的顺序。当你的索引是一个字符串时,它没有排序,正确的排序应该是:

ser3 = Series(['USA','Mexico','Canada'],index = ['0','10','5'])ranger = range(15)

Note: ranger being an integer sequence while index is string sequence, the method isn't going to do much but reindex will work

In [100]: ser3.reindex(ranger,method = 'ffill')
Out[100]: 
0     NaN
1     NaN
2     NaN
3     NaN
4     NaN
5     NaN
6     NaN
7     NaN
8     NaN
9     NaN
10    NaN
11    NaN
12    NaN
13    NaN
14    NaN
dtype: object

希望这有助于使reindex更清晰!


0
投票

原始索引是字符串而不是数字。如果将原始索引更改为数字(例如,index = [0,5,10]),则它可以正常工作。

In [1]: from pandas import Series
   ...: ser3 = Series(['USA','Mexico','Canada'],index = [0,5,10])
   ...: ranger = range(15)
   ...: ser3.reindex(ranger,method = 'ffill')
   ...: 
Out[1]: 
0        USA
1        USA
2        USA
3        USA
4        USA
5     Mexico
6     Mexico
7     Mexico
8     Mexico
9     Mexico
10    Canada
11    Canada
12    Canada
13    Canada
14    Canada
dtype: object

0
投票

也许你可以试着把ffill放出reindex l

ser3.reindex(ranger).ffill()
© www.soinside.com 2019 - 2024. All rights reserved.