开始使用免费开始使用

综合运用(2)

调用函数时有时会出错——即使是您自己写的函数也不例外。别担心!本练习中,您将改进上一章中的 count_entries() 函数,给它加入一个 try-except 代码块。这样,当用户调用 count_entries() 时如果提供了一个不在 DataFrame 中的列名,您的函数就能给出有用的提示信息。

和之前一样,为方便起见,已将 pandas 导入为 pd,并将 'tweets.csv' 文件读入到了 DataFrame tweets_df 中。您之前写过的部分代码也已提供。

本练习是课程的一部分

Python 函数入门

查看课程

练习说明

  • 添加一个 try 代码块,使得当以正确参数调用函数时,函数会处理 DataFrame 并返回结果字典。
  • 添加一个 except 代码块,使得当以不正确方式调用函数时,显示如下错误信息:'The DataFrame does not have a ' + col_name + ' column.'

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Define count_entries()
def count_entries(df, col_name='lang'):
    """Return a dictionary with counts of
    occurrences as value for each key."""

    # Initialize an empty dictionary: cols_count
    cols_count = {}

    # Add try block
    ____:
        # 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

    # Add except block
    ____:
        ____

# Call count_entries(): result1
result1 = count_entries(tweets_df, 'lang')

# Print result1
print(result1)
编辑并运行代码