Python - How to convert pandas dataframe to a dictionary without index?

Given a Pandas DataFrame, we have to convert it to a dictionary without index.
Submitted by Pranit Sharma, on August 09, 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 data.

Dictionaries are used to store heterogeneous data. The data is stored in key:value pair. A dictionary is a collection that is mutable and ordered in nature and does not allow duplicates which means there are unique keys in a dictionary.

A dictionary key can have any type of data as its value, for example, a list, tuple, string, or a dictionary itself.

Convert pandas dataframe to a dictionary without index

Pandas provide a method called pandas.DataFrame.to_dict() method which will allow us to convert a DataFrame into a dictionary but the generated output will have the index values in the form of a key. Sometimes we do not want the index values as the key, in that case, we follow another approach.

Let us understand with the help of an example,

Python program to convert pandas dataframe to a dictionary without index

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Name':['Pranit','Sudhir'],
    'Age':[21,31]
}

# Creating a DataFrame
df = pd.DataFrame(d)

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

# Setting index and converting to dictionary
print("Converted Dictionary:\n",df.to_dict('r'))

Output

The output of the above program is:

Example: Convert pandas dataframe to a dictionary without index

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.