MultiIndex,其中索引之一为元组

时间:2018-07-30 14:42:10

标签: python pandas

我用多索引创建了一个数据框,其中索引之一是一个元组。我无法使用.loc进行索引。

以下是数据框:

a = [['a','a','a','b','b','b','c','c'],[('one',2),('one',1),('two',1),('two',1),('two',2),('one',2),('two',2),('one',1)]]
t_index=pd.MultiIndex.from_tuples(list(zip(*a)),names=['letters','numbers'])

b=[1,4,3,5,7,2,6,1]

df=pd.DataFrame({'position':b},t_index)
print(df)
                  position
letters numbers           
a       (one, 2)         1
        (one, 1)         4
        (two, 1)         3
b       (two, 1)         5
        (two, 2)         7
        (one, 2)         2
c       (two, 2)         6
        (one, 1)         1

当我尝试使用.loc访问时,出现以下错误:

df.loc[('a',('one',2))]
"None of [('one', 2)] are in the [columns]"

我更喜欢将“数字”索引保留为元组而不是两个值,除非确实不建议这样做。有人可以指出我要去哪里哪里或者应该怎么做才能访问索引?

4 个答案:

答案 0 :(得分:1)

您可以使用loc + xs

df.loc['a'].xs(('one',2))

或者:

df.xs(['a', ('one',2)],level=[0,1])

或(更直观)

df.xs(['a', ('one',2)],level=['letters','numbers'])

输出:

                  position
letters numbers 
a   (one, 2)         1

答案 1 :(得分:1)

您也可以只使用document.addEventListener('DOMContentLoaded', function() { // Store the window width var windowWidth = window.innerWidth // Resize Event window.addEventListener("resize", function() { // Check window width has actually changed and it's not just iOS triggering a resize event on scroll if (window.innerWidth != windowWidth) { // Update the window width for next time windowWidth = window.innerWidth // Do stuff here } // Otherwise do nothing }) })

xs

收益:

df.xs(('a',('one',2)), level=[0,1])

答案 2 :(得分:1)

我只是尝试在此处修复您的代码

df[df.index.isin([('a',('one',2))])]
Out[398]: 
                  position
letters numbers           
a       (one, 2)         1

答案 3 :(得分:1)

如果您的索引级别numbers始终包含两个元素,那么我建议您实际上将级别分为两个。

tups = [(letter,) + number for letter, number in df.index]
idx = pd.MultiIndex.from_tuples(tups, names=['letters', 'numbers_0', 'numbers_1'])

df_ = df.set_index(idx)

df_.loc[[('a', 'one', 2)]]

                             position
letters numbers_0 numbers_1          
a       one       2                 1

除此之外,我更喜欢将xslevel一起使用,@rahlf23首先显示