python DataFrame转dict字典过程详解

yipeiwu_com6年前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设计】。

相关文章

基于python2.7实现图形密码生成器的实例代码

具体代码如下所示: #coding:utf8 import random,wx def password(event): a = [chr(i) for i in range(9...

python reduce 函数使用详解

python reduce 函数使用详解

reduce() 函数在 python 2 是内置函数, 从python 3 开始移到了 functools 模块。 官方文档是这样介绍的 reduce(...) reduce(fu...

Python3 Random模块代码详解

描述 random() 方法返回随机生成的一个实数,它在[0,1)范围内。 import random help(random) FUNCTIONS betavariate(a...

Python基于多线程实现ping扫描功能示例

本文实例讲述了Python基于多线程实现ping扫描功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #! python2 import subp...

python append、extend与insert的区别

最近在自学Python语言,看到向列表增加更多数据时被append(),extend(),insert()方法绕晕了。 append 和extend都只需要一个参数,并且自动添加到数组末...