Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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. This method offers several orientation options to structure the output dictionary differently based on your needs.
Basic DataFrame to Dictionary Conversion
Let's start with a simple example using the default orientation ?
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:")
print(df)
print("\nConvert DataFrame into dictionary:")
print(df.to_dict())
Input DataFrame:
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}}
Different Orientation Options
The to_dict() method supports various orientations to format the output ?
import pandas as pd
df = pd.DataFrame(
{
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 35],
"city": ["New York", "London", "Tokyo"]
}
)
print("Original DataFrame:")
print(df)
print("\n1. 'dict' orientation (default):")
print(df.to_dict('dict'))
print("\n2. 'list' orientation:")
print(df.to_dict('list'))
print("\n3. 'records' orientation:")
print(df.to_dict('records'))
print("\n4. 'index' orientation:")
print(df.to_dict('index'))
Original DataFrame:
name age city
0 Alice 25 New York
1 Bob 30 London
2 Charlie 35 Tokyo
1. 'dict' orientation (default):
{'name': {0: 'Alice', 1: 'Bob', 2: 'Charlie'}, 'age': {0: 25, 1: 30, 2: 35}, 'city': {0: 'New York', 1: 'London', 2: 'Tokyo'}}
2. 'list' orientation:
{'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'city': ['New York', 'London', 'Tokyo']}
3. 'records' orientation:
[{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'London'}, {'name': 'Charlie', 'age': 35, 'city': 'Tokyo'}]
4. 'index' orientation:
{0: {'name': 'Alice', 'age': 25, 'city': 'New York'}, 1: {'name': 'Bob', 'age': 30, 'city': 'London'}, 2: {'name': 'Charlie', 'age': 35, 'city': 'Tokyo'}}
Comparison of Orientations
| Orientation | Structure | Best For |
|---|---|---|
'dict' |
Column ? {Index ? Value} | Preserving column structure |
'list' |
Column ? [Values] | Simple column-based data |
'records' |
[{Column ? Value}] | JSON-like row records |
'index' |
Index ? {Column ? Value} | Row-based data access |
Conclusion
Use to_dict() to convert DataFrames to dictionaries. Choose the orientation based on your needs: 'records' for JSON-like format, 'list' for simple arrays, or 'dict' for preserving the original structure.
Advertisements
