为了补充前面的答案,让我解释一下pd.IndexSlice 的工作原理以及它为什么有用。
好吧,关于它的实现没有什么好说的。正如您在source 中所读到的,它只是执行以下操作:
class IndexSlice(object):
def __getitem__(self, arg):
return arg
由此我们看到pd.IndexSlice 只转发__getitem__ 收到的参数。看起来很愚蠢,不是吗?但是,它实际上做了一些事情。
您肯定已经知道,如果您通过括号运算符obj[arg] 访问对象obj,则会调用obj.__getitem__(arg)。对于序列类型对象,arg 可以是整数或slice object。我们很少自己构建切片。相反,我们会为此目的使用切片运算符:(又名省略号),例如obj[0:5].
重点来了。 python 解释器在调用对象的__getitem__(arg) 方法之前将这些切片运算符: 转换为切片对象。因此,IndexSlice.__getItem__() 的返回值实际上是一个切片、一个整数(如果没有使用 :)或它们的元组(如果传递了多个参数)。总之,IndexSlice 的唯一目的是我们不必自己构造切片。这种行为对pd.DataFrame.loc 尤其有用。
我们先来看看下面的例子:
import pandas as pd
idx = pd.IndexSlice
print(idx[0]) # 0
print(idx[0,'a']) # (0, 'a')
print(idx[:]) # slice(None, None, None)
print(idx[0:3]) # slice(0, 3, None)
print(idx[0.1:2.3]) # slice(0.1, 2.3, None)
print(idx[0:3,'a':'c']) # (slice(0, 3, None), slice('a', 'c', None))
我们观察到冒号: 的所有用法都被转换为切片对象。如果将多个参数传递给索引运算符,则参数将转换为 n 元组。
为了演示这对具有多级索引的 pandas 数据框 df 有何用处,让我们看一下以下内容。
# A sample table with three-level row-index
# and single-level column index.
import numpy as np
level0 = range(0,10)
level1 = list('abcdef')
level2 = ['I', 'II', 'III', 'IV']
mi = pd.MultiIndex.from_product([level0, level1, level2])
df = pd.DataFrame(np.random.random([len(mi),2]),
index=mi, columns=['col1', 'col2'])
# Return a view on 'col1', selecting all rows.
df.loc[:,'col1'] # pd.Series
# Note: in the above example, the returned value has type
# pd.Series, because only one column is returned. One can
# enforce the returned object to be a data-frame:
df.loc[:,['col1']] # pd.DataFrame, or
df.loc[:,'col1'].to_frame() #
# Select all rows with top-level values 0:3.
df.loc[0:3, 'col1']
# If we want to create a slice for multiple index levels
# we need to pass somehow a list of slices. The following
# however leads to a SyntaxError because the slice
# operator ':' cannot be placed inside a list declaration.
df.loc[[0:3, 'a':'c'], 'col1']
# The following is valid python code, but looks clumsy:
df.loc[(slice(0, 3, None), slice('a', 'c', None)), 'col1']
# Here is why pd.IndexSlice is useful. It helps
# to create a slice that makes use of two index-levels.
df.loc[idx[0:3, 'a':'c'], 'col1']
# We can expand the slice specification by a third level.
df.loc[idx[0:3, 'a':'c', 'I':'III'], 'col1']
# A solitary slicing operator ':' means: take them all.
# It is equivalent to slice(None).
df.loc[idx[0:3, 'a':'c', :], 'col1'] # pd.Series
# Semantically, this is equivalent to the following,
# because the last ':' in the previous example does
# not add any information about the slice specification.
df.loc[idx[0:3, 'a':'c'], 'col1'] # pd.Series
# The following lines are also equivalent, but
# both expressions evaluate to a result with multiple columns.
df.loc[idx[0:3, 'a':'c', :], :] # pd.DataFrame
df.loc[idx[0:3, 'a':'c'], :] # pd.DataFrame
总之,pd.IndexSlice 在为行和列索引指定切片时有助于提高可读性。
pandas 对这些切片的处理是另一回事。它本质上选择行/列,从最顶层的索引级别开始,并在进一步降低级别时减少选择,具体取决于指定的级别。 pd.DataFrame.loc 是一个拥有自己的 __getitem__() 函数的对象,它可以完成所有这些工作。
正如您已经在您的一个 cmets 中指出的那样,pandas 在某些特殊情况下的行为似乎很奇怪。您提到的两个示例实际上将得出相同的结果。但是,pandas 在内部对它们的处理方式有所不同。
# This will work.
reviews.loc[idx[top_reviewers, 99, :], ['beer_name', 'brewer_id']]
# This will fail with TypeError "unhashable type: 'Index'".
reviews.loc[idx[top_reviewers, 99] , ['beer_name', 'brewer_id']]
# This fixes the problem. (pd.Index is not hashable, a tuple is.
# However, the problem matters only with the second expression.)
reviews.loc[idx[tuple(top_reviewers), 99] , ['beer_name', 'brewer_id']]
诚然,差异是微妙的。