首页 > 解决方案 > 将列转换为 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())

标签: pythonpandasdictionary

解决方案


使用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']}

等等...阅读文档


推荐阅读