pandas get_level_values 多列

pandas get_level_values for multiple columns

有没有办法为多列获取 get_level_values 的结果?

给出以下 DataFrame

         d
a b c     
1 4 10  16
    11  17
  5 12  18
2 5 13  19
  6 14  20
3 7 15  21

我希望获得级别 ac:

的值( 元组列表)
[(1, 10), (1, 11), (1, 12), (2, 13), (2, 14), (3, 15)]

备注:

例如:

a_list = df.index.get_level_values('a').values
c_list = df.index.get_level_values('c').values

print([i for i in zip(a_list,c_list)])
[(1, 10), (1, 11), (1, 12), (2, 13), (2, 14), (3, 15)]

但随着列数的增加,它会变得很麻烦。

df = pd.DataFrame({'a':[1,1,1,2,2,3],'b':[4,4,5,5,6,7,],'c':[10,11,12,13,14,15], 'd':[16,17,18,19,20,21]}).set_index(['a','b','c'])

只要你可以将你想要的索引名称列表传递给select:

,这就不那么麻烦了
df.reset_index()[['a', 'c']].to_dict(orient='split')['data']

我还没有找到直接从索引对象 selecting 级别 'a''b' 的方法,因此使用 reset_index.

请注意 to_dict returns 列表的列表而不是元组:

[[1, 10], [1, 11], [1, 12], [2, 13], [2, 14], [3, 15]]

MultiIndex.tolist() 方法给出了 MultiIndex 中所有级别的元组列表。例如,以您的示例 DataFrame

df.index.tolist()
# => [(1, 4, 10), (1, 4, 11), (1, 5, 12), (2, 5, 13), (2, 6, 14), (3, 7, 15)]

所以这里有两个想法:

  1. 从原始MultiIndex获取元组列表并过滤结果

    [(a, c) for a, b, c in df.index.tolist()]
    # => [(1, 10), (1, 11), (1, 12), (2, 13), (2, 14), (3, 15)]
    

    这种简单方法的缺点是您必须手动指定所需级别的顺序。您可以利用 itertools.compress 来 select 它们的名称。

    from itertools import compress
    
    mask = [1 if name in ['a', 'c'] else 0 for name in df.index.names]
    [tuple(compress(t, mask)) for t in df.index.tolist()]
    # => [(1, 10), (1, 11), (1, 12), (2, 13), (2, 14), (3, 15)]
    
  2. 创建一个具有您想要的级别的 MultiIndex 并对其调用 .tolist()

    df.index.droplevel('b').tolist()
    # => [(1, 10), (1, 11), (1, 12), (2, 13), (2, 14), (3, 15)]
    

    如果你更愿意命名你想要保留的级别——而不是你想要删除的级别——你可以这样做

    df.index.droplevel([level for level in df.index.names
                    if not level in ['a', 'c']]).tolist()
    # => [(1, 10), (1, 11), (1, 12), (2, 13), (2, 14), (3, 15)]
    

简单:

df.index.to_frame().to_numpy()[:, [0,2]]