您的位置:首页 > 编程语言 > Python开发

python DataFrame转dict字典过程详解

2020-02-13 13:57 756 查看

这篇文章主要介绍了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

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python DataFrame dict 字典