首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >附加后Pandas系列.loc()访问错误

附加后Pandas系列.loc()访问错误
EN

Stack Overflow用户
提问于 2014-02-13 01:22:50
回答 1查看 238关注 0票数 1

我有一个多索引的熊猫系列,如下所示。我想向multi_df添加一个新条目(new_series),将其命名为multi_df_appended。但是,当我试图访问不存在的多索引时,我不理解multi_dfmulti_df_appended之间的行为变化。

下面是重现问题的代码。我希望倒数第二行代码:multi_df_appended.loc['five', 'black', 'hard', 'square' ]multi_df一样返回一个空序列,但我得到的却是错误。我在这里做错了什么?

代码语言:javascript
复制
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!?
EN

回答 1

Stack Overflow用户

发布于 2014-02-13 02:08:18

正如@ give回答的那样,如果我执行.sortlevel(0),然后对未知索引运行.loc(),它不会给出“词法排序深度”错误:

代码语言:javascript
复制
multi_df_appended_sorted = multi_df.append(new_series).sortlevel(0)
multi_df_appended_sorted.loc['five', 'black', 'hard', 'square' ]
Series([], dtype: int64)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21735041

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档