ADVERTISEMENT
ADVERTISEMENT

How to Convert a DataFrame to a Dictionary?

Given a Pandas DataFrame, we have to convert it into a Dictionary.
Submitted by Pranit Sharma, on June 20, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data.

Python Dictionary

Dictionary in Python is a collection of data values that is unordered and the data values hold the key:value relationship. The key in the dictionary is unique and holds a single value (homogeneous in nature). Dictionaries in Python are fast and optimized as compared to other data types of Python.

To convert a pandas DataFrame into a dictionary, we will use pandas.DataFrame.to_dict() method.

Syntax:

DataFrame.to_dict(
    orient='dict', 
    into=<class 'dict'>
    )

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python code to convert a DataFrame to a dictionary

# Importing pandas package
import pandas as pd

# Create d DataFrame
df = pd.DataFrame({
    'Name':['Pranit','Sudhir','Raman','Jatin','Apurva','Deepti','Richa','Sheetal'],
    'Age':[20,30,34,28,20,23,19,39]
})

# Display DataFrame
print("Created DataFrame:\n",df,"\n")

# Converting DataFramew to dictionary
dic = df.to_dict()

# Display dictionary
print("Converted Dictionary:\n",dic)

Output:

Example: Convert a DataFrame to a Dictionary

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.