Pandas: Iterate over rows in a DataFrame

Pandas: DataFrame Exercise-21 with Solution

Write a Pandas program to iterate over rows in a DataFrame.

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                   

Python 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 Python skills with w3resource's quiz

Python: Tips of the Day

Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value


def tips_map_values(obj, fn):
  ret = {}
  for key in obj.keys():
    ret[key] = fn(obj[key])
  return ret
users = {
  'Owen': { 'user': 'Owen', 'age': 29 },
  'Eddie': { 'user': 'Eddie', 'age': 15 }

print(tips_map_values(users, lambda u : u['age'])) # {'Owen': 29, 'Eddie': 15}


{'Owen': 29, 'Eddie': 15}