当前位置:首页 » python教程 » 正文

python DataFrame转dict字典过程详解

看: 1016次  时间:2020-12-27  分类 : python教程

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

标签:pandas  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!