【发布时间】:2020-08-09 15:00:49
【问题描述】:
我正在使用 python 3.6、pandas 24.2 并遇到了不同之处。
>>> x = pd.Series(range(3))
>>> x[-1]
>>> x = pd.Series(range(3), index=[0,1,2])
>>> x[-1]
两者都会产生错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/conda3/ml4t/lib/python3.6/site-packages/pandas/core/series.py", line 868, in __getitem__
result = self.index.get_value(self, key)
File "/opt/conda3/ml4t/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 4375, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 81, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 89, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 987, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 993, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: -1
同时
>>> x = pd.Series(range(3), index=['a','b','c'])
>>> x[-1]
2
可以与任何其他形式的索引一起使用。它们是相同的数据结构,但添加某些类型的索引允许负索引,而另一些则不允许?
【问题讨论】:
-
并非如此。它是相同的数据结构。只是索引类型有所不同。为什么?
-
整数索引的问题在于,这可以通过一系列:
x = pd.Series(range(3), index=[1,-1,2])x[-1]在这里返回什么? -
@AMC 不,他们知道这不起作用,问题是为什么它不适用于“正常”系列或给定的整数索引,但适用于 char 索引
-
感谢尼克的澄清。使用日期索引也允许 [-1]。
-
@MarkMeyer,这更像是一个一致性问题。为什么切片不能像 numpy 那样基于 100% 的位置工作并根据需要使用 .loc 。 pandas.pydata.org/pandas-docs/version/0.17.0/… 似乎表明它也是基于 numpy 的。