简体   繁体   English

从多索引 df 获取特定部分,而不会丢失 0 级索引

[英]Getting a specific part from multiindex df, without losing level 0 index

Imagine you have the following multiindexed dataframe想象一下,您有以下多索引 dataframe

pd.DataFrame({('0-Engajados', 'affiliate'): 119,
     ('0-Engajados', 'attendance bot'): 7,
     ('1-Onboarding + Retorno', 'affiliate'): 118,
     ('1-Onboarding + Retorno', 'attendance bot'): 7})

And you wanted to grab everyone who has a level 0 index equal '0-Engajados' but without losing, the index part.你想抓住每个 0 级索引等于 '0-Engajados' 但又不会丢失索引部分的人。 It is worh noting that the second index values vary, so iloc not quite an option.值得注意的是,第二个索引值会有所不同,因此 iloc 不是一个很好的选择。

Wanted end result想要的最终结果

pd.DataFrame({('0-Engajados', 'affiliate'): 119,
     ('0-Engajados', 'attendance bot'): 7})

I tried df.loc['0-Engajados']我试过df.loc['0-Engajados']

but that loses me the first index is there a way to grab it without losing it?但这让我失去了第一个索引有没有办法在不丢失的情况下抓住它?

You can wrap your selection in a list to preserve its level:您可以将您的选择包装在一个列表中以保留其级别:

import pandas as pd

df = pd.DataFrame({('0-Engajados', 'affiliate'): [119],
     ('0-Engajados', 'attendance bot'): [7],
     ('1-Onboarding + Retorno', 'affiliate'): [118],
     ('1-Onboarding + Retorno', 'attendance bot'): [7]})

print(df)
  0-Engajados                1-Onboarding + Retorno               
    affiliate attendance bot              affiliate attendance bot
0         119              7                    118              7


print(df.loc[:, ['0-Engajados']])
  0-Engajados               
    affiliate attendance bot
0         119              7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM