栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python-从嵌套字典中的项目构造pandas DataFrame

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python-从嵌套字典中的项目构造pandas DataFrame

大熊猫MultiIndex由元组列表组成。因此,最自然的方法是调整输入字典的形状,使其键为与所需的多索引值相对应的元组。然后,你可以使用

pd.Dataframe.from_dict
,使用选项来构建数据框
orient='index'

user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},       'Category 2': {'att_1': 23, 'att_2': 'another'}},  15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},       'Category 2': {'att_1': 30, 'att_2': 'bar'}}}pd.Dataframe.from_dict({(i,j): user_dict[i][j]      for i in user_dict.keys()      for j in user_dict[i].keys()}, orient='index')    att_1     att_212 Category 1      1  whatever   Category 2     23   another15 Category 1     10       foo   Category 2     30       bar

一种替代方法是通过串联组件数据框来构建数据框:

user_ids = []frames = []for user_id, d in user_dict.iteritems():    user_ids.append(user_id)    frames.append(pd.Dataframe.from_dict(d, orient='index'))pd.concat(frames, keys=user_ids)    att_1     att_212 Category 1      1  whatever   Category 2     23   another15 Category 1     10       foo   Category 2     30       bar


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/393805.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号