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.

Diese Übung ist Teil des Kurses

Practicing Coding Interview Questions in Python

Kurs anzeigen

Anleitung zur Übung

  • 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.

Interaktive Übung zum Anfassen

Probieren Sie diese Übung aus, indem Sie diesen Beispielcode ausführen.

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)