假设我有一个 pandas Series
,并且我想访问特定索引处的一组元素,如下所示:
In [1]:
from pandas import Series
import numpy as np
s = Series(np.arange(0,10))
In [2]: s.loc[[3,7]]
Out[2]:
3 3
7 7
dtype: int64
.loc
方法接受 list
作为此类选择的参数。 .iloc
和 .ix
方法的工作方式相同。
但是,如果我使用 tuple
作为参数,.loc
和 .iloc
都会失败:
In [5]: s.loc[(3,7)]
---------------------------------------------------------------------------
IndexingError Traceback (most recent call last)
........
IndexingError: Too many indexers
In [6]: s.iloc[(3,7)]
---------------------------------------------------------------------------
IndexingError Traceback (most recent call last)
........
IndexingError: Too many indexers
并且 .ix
产生一个奇怪的结果:
In [7]: s.ix[(3,7)]
Out[7]: 3
现在,我知道你甚至不能用原始的 python list
来做到这一点:
In [27]:
x = list(range(0,10))
x[(3,7)]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-27-cefdde088328> in <module>()
1 x = list(range(0,10))
----> 2 x[(3,7)]
TypeError: list indices must be integers or slices, not tuple
要从列表
中检索一组特定索引,您需要使用推导式 as explained here .
但另一方面,使用 tuple
从 pandas DataFrame
中选择行似乎适用于所有三种索引方法。下面是使用 .loc
方法的示例:
In [8]:
from pandas import DataFrame
df = DataFrame({"x" : np.arange(0,10)})
In [9]:
df.loc[(3,7),"x"]
Out[9]:
3 3
7 7
Name: x, dtype: int64
我的三个问题是:
- 为什么
Series
索引器不接受元组
?看起来
使用元组
很自然,因为所需索引的集合是
不可变的、一次性的参数。这仅仅是为了 模仿list
界面? - 对于奇怪的
Series
.ix
结果有何解释? - 为什么在这个问题上
Series
和DataFrame
之间存在不一致?
最佳答案
我认为第一个问题的答案是元组
用于在MultiIndex
中定位。我认为对于后两个问题没有很好的答案,除非您分别在代码中暴露了错误和不一致(这并不难做到:))。
所以 Series
会提示,因为你没有
MultiIndex
或者更一般地说,元组的长度大于索引中的级别数。
DataFrame
可能应该以相同的方式使用react,但事实并非如此。
我认为最安全的方法是为 MultiIndex 保留元组并使用列表/数组/系列来索引多行。
作为旁注,您可以使用元组列表/数组来选择 MultiIndex
中的多行。
关于python - Pandas 索引器方法和元组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36197842/