ValueError: index must be monotonic increasing or decreasing

余生颓废 提交于 2020-01-10 05:38:06

问题


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

here ranger = range(15)

I get an error while using Forward fill in iPython

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

回答1:


As David said it was due to index being a string. But why were you getting the "Index not monotonic Error" and the answer to that is - For reindexing methods to work, your index must be in sorted/monotonic/increasing order. And when your index was a string, it wasn't sorted, correct sorting should have been:

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

Hope this helps and makes reindex clearer !!




回答2:


maybe you can try to put the ffill out of reindex l

ser3.reindex(ranger).ffill()



回答3:


There's something about the original index being string and not numeric. If you change the original index to be numeric (e.g., index=[0, 5, 10]), it works correctly.

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


来源:https://stackoverflow.com/questions/31285508/valueerror-index-must-be-monotonic-increasing-or-decreasing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!