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
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
- python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
- 在Python中使用defaultdict初始化字典以及应用方法
- 解决Python获取字典dict中不存在的值时出错问题
- python 实现将字典dict、列表list中的中文正常显示方法
- Python实现字典(dict)的迭代操作示例
- python 将字符串转换成字典dict的各种方式总结
- Python中如何优雅的合并两个字典(dict)方法示例
- Python pandas.DataFrame 找出有空值的行
- Python pandas.DataFrame调整列顺序及修改index名的方法
- 使用Python向DataFrame中指定位置添加一列或多列的方法
相关文章推荐
- Python数据类型详解(四)字典:dict
- Python中字典(dict)详解
- Python数据类型之Dict字典实例详解
- Python——dict()字典详解
- python字典DICT类型合并详解
- Python - 字典(dict) 详解 及 代码
- python——Container之字典(dict)详解
- Python - 字典(dict) 详解 及 代码
- python 字典(dict)详解
- python报错:使用lgb过程中报错:DataFrame.dtypes for data must be int, float or bool
- mongodb取出json,利用python转成dataframe(dict-to-dataframe)
- Python 之 字典(dict)详解
- python dict to dataframe
- 详解python中的json和字典dict
- Python中pandas dataframe删除一行或一列:drop函数详解
- Python - 字典(dict) 详解 及 代码
- Python中pandas dataframe删除一行或一列:drop函数详解
- Python 字典(dict)剖析详解
- python dict 字典 以及 赋值 引用的一些实例(详解)
- Python数据类型详解(四)字典:dict