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.
本练习是课程的一部分
Practicing Coding Interview Questions in Python
练习说明
- Traverse through the columns in the
heroesDataFrame. - Retrieve the values stored in
seriesin a list form. - Traverse through unique categories in
values. - Count the appearance of
categoryinvalues.
交互式实操练习
通过完成这段示例代码来试试这个练习。
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)