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
Write a program in Python to print dataframe rows as orderDict with a list of tuple values
In Pandas, you can convert DataFrame rows to OrderedDict objects with list of tuple values. This is useful when you need to maintain the order of columns and access row data in a structured dictionary format.
Understanding the Problem
When working with DataFrames, sometimes you need each row as an OrderedDict where each column-value pair is represented as a tuple. The expected output format is ?
OrderedDict([('Index', 0), ('Name', 'Raj'), ('Age', 13), ('City', 'Chennai'), ('Mark', 80)])
OrderedDict([('Index', 1), ('Name', 'Ravi'), ('Age', 12), ('City', 'Delhi'), ('Mark', 90)])
OrderedDict([('Index', 2), ('Name', 'Ram'), ('Age', 13), ('City', 'Chennai'), ('Mark', 95)])
Solution Steps
To solve this problem, follow these steps ?
Create a DataFrame with sample data
Use
df.itertuples(name='stud')to iterate through rows as named tuplesConvert each named tuple to OrderedDict using
_asdict()methodPrint the resulting OrderedDict for each row
Example
Let's implement the solution with a complete example ?
import pandas as pd
# Create sample data
students = [('Raj', 13, 'Chennai', 80),
('Ravi', 12, 'Delhi', 90),
('Ram', 13, 'Chennai', 95)]
# Create DataFrame
df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Mark'])
print("DataFrame is:")
print(df)
print()
# Convert each row to OrderedDict
for row in df.itertuples(name='stud'):
dict_row = row._asdict()
print(dict_row)
DataFrame is:
Name Age City Mark
0 Raj 13 Chennai 80
1 Ravi 12 Delhi 90
2 Ram 13 Chennai 95
OrderedDict([('Index', 0), ('Name', 'Raj'), ('Age', 13), ('City', 'Chennai'), ('Mark', 80)])
OrderedDict([('Index', 1), ('Name', 'Ravi'), ('Age', 12), ('City', 'Delhi'), ('Mark', 90)])
OrderedDict([('Index', 2), ('Name', 'Ram'), ('Age', 13), ('City', 'Chennai'), ('Mark', 95)])
How It Works
The itertuples() method creates named tuples for each row, where:
name='stud'sets the named tuple class name_asdict()converts the named tuple to an OrderedDictThe 'Index' field represents the DataFrame row index
Column names become keys in the OrderedDict
Conclusion
Use df.itertuples(name='custom') combined with _asdict() to convert DataFrame rows into OrderedDict objects. This approach preserves column order and provides easy access to row data as key-value pairs.
