pandas ValueError:索引必须单调递增或递减
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31285508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ValueError: index must be monotonic increasing or decreasing
提问by Varun
ser3 = Series(['USA','Mexico','Canada'],index = ['0','5','10'])
ser3 = Series(['USA','Mexico','Canada'],index = ['0','5','10'])
here ranger = range(15)
这里 ranger = range(15)
I get an error while using Forward fill in iPython
在 iPython 中使用正向填充时出现错误
ser3.reindex(ranger,method = 'ffill')
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
回答by haris khan
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)
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
注意: ranger 是一个整数序列,而 index 是字符串序列,该方法不会做太多,但 reindex 会起作用
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 !!
希望这会有所帮助并使重新索引更清晰!
回答by Charles q
maybe you can try to put the ffillout of reindexl
也许你可以尝试把ffill出reindex升
ser3.reindex(ranger).ffill()
回答by davidshinn
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.
有一些关于原始索引是字符串而不是数字的东西。如果您将原始索引更改为数字(例如,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

