python DataFrame转dict字典过程详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python DataFrame转dict字典过程详解

  2021-04-02 我要评论

这篇文章主要介绍了python DataFrame转dict字典过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

背景:将商品id以及商品类别作为字典的键值映射,生成字典,原为DataFrame

# 创建一个DataFrame
# 列值类型均为int型
import pandas as pd
item = pd.DataFrame({'item_id': [100120, 10024504, 1055460], 'item_category': [87974, 975646, 87974]}, index=[0, 1, 2])
item

# 将item_id,item_category两列数值转为dict字典
# 注意:同种商品类别肯定会对应不同商品,即一对多,进行字典映射,一定要是item_id作为键,item_category作为值
# 由于原始数据为int类型,结果将是字符串之间的映射,因此需要对列值进行数据类型转换
item.item_id = (item['item_id']).astype(str)
item.item_category = (item['item_category']).astype(str)
item_dict = item.set_index('item_id')['item_category'].to_dict()
item_dict

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们