我有一个多索引的熊猫系列,如下所示。我想向multi_df添加一个新条目(new_series),将其命名为multi_df_appended。但是,当我试图访问不存在的多索引时,我不理解multi_df和multi_df_appended之间的行为变化。
下面是重现问题的代码。我希望倒数第二行代码: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!?发布于 2014-02-13 02:08:18
正如@ give回答的那样,如果我执行.sortlevel(0),然后对未知索引运行.loc(),它不会给出“词法排序深度”错误:
multi_df_appended_sorted = multi_df.append(new_series).sortlevel(0)
multi_df_appended_sorted.loc['five', 'black', 'hard', 'square' ]
Series([], dtype: int64)https://stackoverflow.com/questions/21735041
复制相似问题