拼接 MultiIndex(.loc 不工作)

Splicing MultiIndex (.loc not working)

我在切片 MultiIndex 时遇到问题。到目前为止,我已经尝试了几种技术,但除了一种我没有让它们发挥作用。 我的 DataFrame 由几行组成,如下所示:

means


Out[25]: 
                              Total         DL         DM
Mouse Genotype Intensity                                 
455   cre      s          15.114886  13.626841  16.602930
               w          41.419970  33.916706  48.923234

554   wt       s          19.348266  13.747603  24.948928
               w          41.563015  37.336228  45.789802

我想做的是通过基因型拼接我的 df。 最简单的方法当然是按索引切片,例如

    means[0:2]

但由于我有多个数据框和更多数据,所以我正在寻找一种更优雅的方式。

    means.loc[('cre')]

已经适用于相同的数据框(虽然行数较少)不适用于这个数据框,因为它一直给我 Keyerror:'cre'

当我尝试使用索引器和其他方法时,我偶然发现我不断收到 'cre' 不在索引中的错误。但是,当我尝试按名称而不是级别时,也会发生同样的情况。我不明白为什么会这样。

如果有人能帮助我,那就太好了!谢谢!

解决方案 1:pd.IndexSlice

df.loc[pd.IndexSlice[:, 'cre', :], :]

                              Total         DL         DM
Mouse Genotype Intensity                                 
455   cre      s          15.114886  13.626841  16.602930
               w          41.419970  33.916706  48.923234

解决方案 2:swaplevelloc

要使用loc['cre']'cre'需要在多索引的第一层。交换关卡可以解决这个问题。

df.swaplevel(0, 1).loc['cre']

                     Total         DL         DM
Mouse Intensity                                 
455   s          15.114886  13.626841  16.602930
      w          41.419970  33.916706  48.923234

解决方案 3:xs

print df.xs('cre', level=1)

                     Total         DL         DM
Mouse Intensity                                 
455   s          15.114886  13.626841  16.602930
      w          41.419970  33.916706  48.923234

print df.xs('cre', level=1, drop_level=False)

                              Total         DL         DM
Mouse Genotype Intensity                                 
455   cre      s          15.114886  13.626841  16.602930
               w          41.419970  33.916706  48.923234

时机

xs 似乎是最高效的。