Categories
Python Answers

How to convert a Python Pandas DataFrame to a dictionary?

Spread the love

Sometimes, we want to convert a Python Pandas DataFrame to a dictionary.

In this article, we’ll look at how to convert a Python Pandas DataFrame to a dictionary.

How to convert a Python Pandas DataFrame to a dictionary?

To convert a Python Pandas DataFrame to a dictionary, we call to_dict.

For instance, we write

df = pd.DataFrame({'a': ['red', 'yellow', 'blue'], 'b': [0.5, 0.25, 0.125]})
df.to_dict('dict')

to create the data frame df.

Then we call to_dict with 'dict' to return the dictionary from the df data frame.

Conclusion

To convert a Python Pandas DataFrame to a dictionary, we call to_dict.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *