综合练习(3)
在上一个练习中,您基于函数 count_entries() 添加了一个 try-except 代码块。这样当用户调用 count_entries() 并传入一个 DataFrame 中不存在的列名时,就能获得有用的提示信息。在本练习中,当用户提供的列名不在 DataFrame 中时,您将改为抛出一个 ValueError。
同样为方便起见,已将 pandas 以 pd 导入,并将 'tweets.csv' 文件读入到了 DataFrame tweets_df 中。您之前编写的部分代码也已提供。
本练习是课程的一部分
Python 函数入门
练习说明
- 如果
col_name不是 DataFramedf的列,请抛出一个ValueError 'The DataFrame does not have a ' + col_name + ' column.'。 - 调用新的函数
count_entries()来分析tweets_df的'lang'列。将结果存入result1。 - 打印
result1。此步骤已为您完成,直接点击 "Submit Answer" 查看结果。在下一个练习中,您将看到它会按需抛出ValueError。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define count_entries()
def count_entries(df, col_name='lang'):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Raise a ValueError if col_name is NOT in DataFrame
if col_name not in df.columns:
____
# Initialize an empty dictionary: cols_count
cols_count = {}
# Extract column from DataFrame: col
col = df[col_name]
# Iterate over the column in DataFrame
for entry in col:
# If entry is in cols_count, add 1
if entry in cols_count.keys():
cols_count[entry] += 1
# Else add the entry to cols_count, set the value to 1
else:
cols_count[entry] = 1
# Return the cols_count dictionary
return cols_count
# Call count_entries(): result1
____
# Print result1
print(result1)