2017-10-07 35 views
3

我有一個多指標數據幀是這樣的:爲什麼我在切片數據框中看到所有原始索引元素?

import pandas as pd 
import numpy as np 


df = pd.DataFrame({'ind1': list('aaaaaaaaabbbbbbbbb'), 
        'ind2': list('cccdddeeecccdddeee'), 
        'ind3': list(range(3))*6, 
        'val1': list(range(100, 118)), 
        'val2': list(range(70, 88))}) 

df_mult = df.set_index(['ind1', 'ind2', 'ind3']) 

       val1 val2 
ind1 ind2 ind3    
a c 0  100 70 
      1  101 71 
      2  102 72 
    d 0  103 73 
      1  104 74 
      2  105 75 
    e 0  106 76 
      1  107 77 
      2  108 78 
b c 0  109 79 
      1  110 80 
      2  111 81 
    d 0  112 82 
      1  113 83 
      2  114 84 
    e 0  115 85 
      1  116 86 
      2  117 87 

我現在可以使用.loc這樣

df_subs = df_mult.loc[pd.IndexSlice['a', ['c', 'd'], :], :] 

這給選擇它的一個子集的預期

   val1 val2 
ind1 ind2 ind3    
a c 0  100 70 
      1  101 71 
      2  102 72 
    d 0  103 73 
      1  104 74 
      2  105 75 

當我打印

df_subs.index 

我得到

MultiIndex(levels=[[u'a', u'b'], [u'c', u'd', u'e'], [0, 1, 2]], 
      labels=[[0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]], 
      names=[u'ind1', u'ind2', u'ind3']) 

爲什麼仍級別0 b並不僅僅是a

這可能會成爲一個問題,如果我想使用其他的索引的元素。然後

df_subs.index.levels[0] 

給我

Index([u'a', u'b'], dtype='object', name=u'ind1') 

然而,

df_subs.index.get_level_values('ind1').unique() 

給我

Index([u'a'], dtype='object', name=u'ind1') 

看起來不一致給我。

這是錯誤還是預期行爲?

+1

我想知道爲什麼也:) – Wen

回答

3

有關GitHub圍繞此行爲的討論here

簡而言之,您看到的級別不是從您實際觀察的MultiIndex中的值計算的 - 在您首次設置MultiIndex後,未觀察的級別將通過索引持續存在。這允許在所有視圖和一些MultiIndex的副本之間共享級索引,這是很好的記憶方式 - 即df_multdf_subs在內存中共享相同的底層索引。

如果您有一個需要重新計算級別的例子來擺脫未使用的級別並創建一個新的MultiIndex,則可以使用MultiIndex.remove_unused_levels()

在你的情況

>>> df_subs.index.remove_unused_levels().levels[0] 
Index(['a'], dtype='object', name='ind1') 
+1

待辦事項讀者:'MultiIndex.remove_unused_levels()'是*新*法大熊貓版本20起。 – Parfait

相關問題