Pandas DataFrame: Iterate over rows in a DataFrame
Pandas: DataFrame Exercise-21 with Solution
Write a Pandas program to iterate over rows in a DataFrame.
Sample Python dictionary data and list labels:
exam_data = [{'name':'Anastasia', 'score':12.5}, {'name':'Dima','score':9}, {'name':'Katherine','score':16.5}]
Sample Solution :
Python Code :
import pandas as pd
import numpy as np
exam_data = [{'name':'Anastasia', 'score':12.5}, {'name':'Dima','score':9}, {'name':'Katherine','score':16.5}]
df = pd.DataFrame(exam_data)
for index, row in df.iterrows():
print(row['name'], row['score'])
Sample Output:
Anastasia 12.5 Dima 9.0 Katherine 16.5
Explanation:
The above code first creates a Pandas DataFrame called ‘df’ using a list of dictionaries containing information about exam scores for three people.
It then iterates over the rows of the DataFrame using the iterrows() method, which returns an iterator yielding index and row data as tuples. For each row, the code prints the values of the name and score columns using print() function.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to insert a new column in existing DataFrame.
Next: Write a Pandas program to get list from DataFrame column headers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/pandas/python-pandas-data-frame-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics