python - 将列转换为 python 字典
问题描述
如何将具有多列的 df 转换为字典?反转此代码的工作流程
import pandas as pd
import numpy as np
df= pd.DataFrame({'Name':['Vikram','John', 'Alex','Paul','Andrew','Rafel' ],
'Age':[28,39,21,50,35,43],
'Department':['HR', 'Finance','IT','HR','IT','IT'],
'Country':['USA','India','Germany','USA','India','India'] })
print(df.head())
解决方案
使用df.to_dict
相反的pd.DataFrame.from_dict
:
>>> ORIENT = 'dict'
>>> df.to_dict(orient=ORIENT)
{'Name': {0: 'Vikram',
1: 'John',
2: 'Alex',
3: 'Paul',
4: 'Andrew',
5: 'Rafel'},
'Age': {0: 28, 1: 39, 2: 21, 3: 50, 4: 35, 5: 43},
'Department': {0: 'HR', 1: 'Finance', 2: 'IT', 3: 'HR', 4: 'IT', 5: 'IT'},
'Country': {0: 'USA',
1: 'India',
2: 'Germany',
3: 'USA',
4: 'India',
5: 'India'}}
>>> ORIENT = 'list'
>>> df.to_dict(orient=ORIENT)
{'Name': ['Vikram', 'John', 'Alex', 'Paul', 'Andrew', 'Rafel'],
'Age': [28, 39, 21, 50, 35, 43],
'Department': ['HR', 'Finance', 'IT', 'HR', 'IT', 'IT'],
'Country': ['USA', 'India', 'Germany', 'USA', 'India', 'India']}
等等...阅读文档
推荐阅读
- sql - 分组和构造消息
- git - 带有嵌套子模块的 git add 后“未暂存更改”
- php - 浏览器中 AJAX 调用和“复制为 cURL”的不同行为
- reactjs - 如何在多对一关系中将子数据数组发送到 api 平台?
- ibm-cloud - 无法再在 Watson Assistant 中选择多个词作为上下文实体
- php - Bootstrap 4 分页在 Larave 8 中无法正常工作
- pyspark - Spark 读取 csv 模式
- javascript - 在不使用父对象的情况下访问对象子属性
- java - 如何防止/禁用 Groovy 脚本中的 AST 转换?
- asp.net-core - 何时在 IHttpClientFactory 中使用 Named HttpClient 和 Basic HttpClient