Examples of how to convert a dataframe to a dictionary with pandas in python:
Table of contents
Convert a dataframe to a dictionary with to_dict()
To convert a dataframe (called for example df) to a dictionary, a solution is to use pandas.DataFrame.to_dict
df.to_dict()
An example:
Create and transform a dataframe to a dictionary
Let's create a simple dataframe
import pandas as pd
import numpy as np
import random
data_dic = {'Name':['Bob','Franck','Emma', 'Lucas'],
'Age':[12,42,27,8]}
df = pd.DataFrame(data_dic)
print(df)
which returns
Name Age
0 Bob 12
1 Franck 42
2 Emma 27
3 Lucas 8
Example 1: to_dict()
To convert a dataframe to a dictionary, a solution is to use to_dict() without arguments:
dict_from_df = df.to_dict()
print(dict_from_df)
which returns
{'Name': {0: 'Bob', 1: 'Franck', 2: 'Emma', 3: 'Lucas'},
'Age': {0: 12, 1: 42, 2: 27, 3: 8}}
Note that
dic_from_df == data_dic
returns here
False
The two dictionaries data_dic and dic_from_df are not the same.
Example 2: to_dict('list')
To get the same dictionary just add here "list":
dic_from_df = df.to_dict('list')
dic_from_df
which returns
{'Name': ['Bob', 'Franck', 'Emma', 'Lucas'], 'Age': [12, 42, 27, 8]}
and
dic_from_df == data_dic
returns then
True
Example 3: to_dict('dict')
dic_from_df = df.to_dict('dict')
dic_from_df
returns
{'Name': {0: 'Bob', 1: 'Franck', 2: 'Emma', 3: 'Lucas'},
'Age': {0: 12, 1: 42, 2: 27, 3: 8}}
Example 4: to_dict('series')
dic_from_df = df.to_dict('series')
dic_from_df
returns
{'Name': 0 Bob
1 Franck
2 Emma
3 Lucas
Name: Name, dtype: object,
'Age': 0 12
1 42
2 27
3 8
Name: Age, dtype: int64}
Example 5: to_dict('split')
dic_from_df = df.to_dict('split')
dic_from_df
returns
{'index': [0, 1, 2, 3],
'columns': ['Name', 'Age'],
'data': [['Bob', 12], ['Franck', 42], ['Emma', 27], ['Lucas', 8]]}
Example 6: to_dict('records')
dic_from_df = df.to_dict('records')
dic_from_df
returns
[{'Name': 'Bob', 'Age': 12},
{'Name': 'Franck', 'Age': 42},
{'Name': 'Emma', 'Age': 27},
{'Name': 'Lucas', 'Age': 8}]
Example 7 to_dict('index')
dic_from_df = df.to_dict('index')
dic_from_df
returns
{0: {'Name': 'Bob', 'Age': 12},
1: {'Name': 'Franck', 'Age': 42},
2: {'Name': 'Emma', 'Age': 27},
3: {'Name': 'Lucas', 'Age': 8}}