close

How to convert dataframe to dictionary in pandas WITHOUT index

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to convert dataframe to dictionary in pandas WITHOUT index in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to convert dataframe to dictionary in pandas WITHOUT index?

  1. How to convert dataframe to dictionary in pandas WITHOUT index?

    Try this: d = df.set_index('name')['coverage'].to_dict() which will convert your dataframe to a series and output that.

  2. convert dataframe to dictionary in pandas WITHOUT index

    Try this: d = df.set_index('name')['coverage'].to_dict() which will convert your dataframe to a series and output that.

Method 1

When I see your dataset with 2 columns I see a series and not a dataframe.

Try this: d = df.set_index('name')['coverage'].to_dict() which will convert your dataframe to a series and output that.

However, if your intent is to have more columns and not a common key you could store them in an array instead using ‘records’. d = df.to_dict('r'). `

Runnable code:

import pandas as pd

df = pd.DataFrame({
    'name': ['Jason'],
    'coverage': [25.1]
})

print(df.to_dict())
print(df.set_index('name')['coverage'].to_dict())
print(df.to_dict('r'))

Returns:

{'name': {0: 'Jason'}, 'coverage': {0: 25.1}}
{'Jason': 25.1}
[{'name': 'Jason', 'coverage': 25.1}]

And one more thing, try to avoid to use variable name dict as it is reserved.

Method 2

dict1 = df.to_dict('records')

or

dict2 = df.to_dict('list')

list: keys are column names, values are lists of column data

records: each row becomes a dictionary where key is column name and value is the data in the cell

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read