这个问题部分是为了帮助我理解多索引上下文中的lex-sorting。
假设我有一些MultiIndexed DataFrame df,并且对于我想要使用的索引:
a = (1, 1, 1)
所以从我写的数据帧中提取值:
df.loc[a, df.columns[i]]
哪个有效。但以下情况并非如此:
df.loc[list(a), df.columns[i]]
给我错误:
*** KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (1), lexsort depth (0)'
为什么会这样?
另外,另一个问题是,以下表现警告意味着什么?
PerformanceWarning: indexing past lexsort depth may impact performance.
答案 0 :(得分:7)
我将使用.loc
为
df
之间的区别
0 1 2
first second
bar one 4 4 7
two 3 4 7
foo one 8 1 8
two 7 5 4
这里df.loc[('foo', 'two')]
返回由此元组索引的行,即(7,5,4)。该参数指定多索引的两个级别。
但df.loc[['foo', 'two']]
表示您希望所有具有多索引最高级别的行 'foo'或'two'。列表表示这些是您想要的选项,并且由于每个选项中只提供一个级别,因此选择基于第一个(最左侧)级别。结果:
0 1 2
first second
foo one 8 1 8
two 7 5 4
(由于没有以'two'开头的多重指示,只有那些'foo'存在。)
如果没有看到你的数据帧,我无法分辨出这种差异会导致获得KeyError,但我希望现在差异很明显。