2014-02-12 41 views
1

我有一個多指標熊貓系列如下。我想添加一個新條目(new_series)至multi_df,將其稱爲multi_df_appended。但是我不明白multi_dfmulti_df_appended之間的行爲變化,當我嘗試訪問不存在的多索引時。熊貓系列.loc()訪問錯誤後追加

下面是重現問題的代碼。我想倒數第二行代碼:multi_df_appended.loc['five', 'black', 'hard', 'square' ]返回一個空的系列,就像它與multi_df一樣,但是我得到了給出的錯誤。我在這裏做錯了什麼?

df = pd.DataFrame({'id' : range(1,9), 
        'code' : ['one', 'one', 'two', 'three', 
           'two', 'three', 'one', 'two'], 
        'colour': ['black', 'white','white','white', 
          'black', 'black', 'white', 'white'], 
        'texture': ['soft', 'soft', 'hard','soft','hard', 
             'hard','hard','hard'], 
        'shape': ['round', 'triangular', 'triangular','triangular','square', 
             'triangular','round','triangular'] 
        }, columns= ['id','code','colour', 'texture', 'shape']) 
multi_df = df.set_index(['code','colour','texture','shape']).sort_index()['id'] 

# try to access a non-existing multi-index combination: 
multi_df.loc['five', 'black', 'hard', 'square' ] 
Series([], dtype: int64) # returns an empty Series as desired/expected. 

# append multi_df with a new row 
new_series = pd.Series([9], index = [('four', 'black', 'hard', 'round')]) 
multi_df_appended = multi_df.append(new_series) 

# now try again to access a non-existing multi-index combination: 
multi_df_appended.loc['five', 'black', 'hard', 'square' ] 
error: 'MultiIndex lexsort depth 0, key was length 4' # now instead of the empty Series, I get an error!? 
+0

這些都提高在0.13.1;你的第一個鍵不存在,所以你得到一個''KeyError'',第二個錯誤是不言自明的,請看這裏:http://pandas-docs.github.io/pandas-docs-travis/indexing.html#需要進行排序的多索引 – Jeff

+0

@Jeff,謝謝。 'multi_df.loc ['five','black','hard','square']'我沒有真正遇到錯誤,'KeyError'是什麼意思?用'multi_df_appended.loc ['five','black','hard','square']',我得到lexsort dept錯誤。所以,我嘗試'multi_df_appended.sortlevel(X)',在嘗試訪問不存在的索引之前,我用0,1,2,3替換X,但仍然得到相同的lexsort深度錯誤。 – Rhubarb

+0

你分配了一個新值嗎?,大多數方法返回一個新的對象 – Jeff

回答

2

由於@Jeff回答,如果我做.sortlevel(0),然後運行.loc()未知指數,它並沒有給「lexsort深度」錯誤:

multi_df_appended_sorted = multi_df.append(new_series).sortlevel(0) 
multi_df_appended_sorted.loc['five', 'black', 'hard', 'square' ] 
Series([], dtype: int64) 
+2

gr8。通常這就是你希望事先創建一個多索引框架(並對其進行分類)的原因,可能還有nan值。請查看http://pandas.pydata.org/pandas-docs/stable/indexing.html?highlight=from_product#creating-a-multiindex-hierarchical-index-object – Jeff