Get startedGet started for free

Traversing a DataFrame

Let's iterate through a DataFrame! You are given the heroes DataFrame you're already familiar with. This time, it contains only categorical data and no missing values. You have to create the following dictionary from this dataset:

  • Each key is a column name.
  • Each value is another dictionary:
    • Each key is a unique category from the column.
    • Each value is the amount of heroes falling into this category.

Tip: a Series object is also an Iterable. It traverses through the values it stores when you put it in a for loop or pass it to list(), tuple(), or set() initializers.

This exercise is part of the course

Practicing Coding Interview Questions in Python

View Course

Exercise instructions

  • Traverse through the columns in the heroes DataFrame.
  • Retrieve the values stored in series in a list form.
  • Traverse through unique categories in values.
  • Count the appearance of category in values.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

column_counts = dict()

# Traverse through the columns in the heroes DataFrame
for column_name, series in ____:
    # Retrieve the values stored in series in a list form
    values = ____(____)
    category_counts = dict()  
    # Traverse through unique categories in values
    for category in ____(values):
        # Count the appearance of category in values
        category_counts[category] = values.____(____)
    
    column_counts[column_name] = category_counts
    
print(column_counts)
Edit and Run Code