
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to convert a DataFrame into a dictionary in Pandas?
To convert a Pandas DataFrame into a dictionary, we can use the to_dict() method. Let's take an example and see how it's done.
Steps
- Create two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
- Print the input DataFrame, df.
- Convert the DataFrame into a dictionary using to_dict() method and print it.
Example
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 7, 5, 1], "z": [9, 3, 5, 1] } ) print "Input DataFrame is:\n", df print "Convert DataFrame into dictionary: \n", df.to_dict()
Output
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Convert DataFrame into dictionary: {'x': {0: 5, 1: 2, 2: 7, 3: 0}, 'y': {0: 4, 1: 7, 2: 5, 3: 1}, 'z': {0: 9, 1: 3, 2: 5, 3: 1}}
- Related Articles
- Python - Convert list of nested dictionary into Pandas Dataframe
- Python Pandas - Convert Nested Dictionary to Multiindex Dataframe
- How to create a pandas DataFrame using a dictionary?
- Write a program in Python Pandas to convert a dataframe Celsius data column into Fahrenheit
- Convert a Pandas DataFrame to a NumPy array
- How to convert a list collection into a dictionary in Java?
- Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?
- Python - Convert a set into dictionary
- Combining two Series into a DataFrame in Pandas
- How to Merge multiple CSV Files into a single Pandas dataframe ?
- Python - Convert one datatype to another in a Pandas DataFrame
- How I can convert a Python Tuple into Dictionary?
- How to read a JSON file into a DataFrame using Python Pandas library?
- Convert two lists into a dictionary in Python
- How to Merge all CSV Files into a single dataframe – Python Pandas?

Advertisements