开始使用免费开始使用

综合应用(2)

太好了!您已经把上一章的 Twitter 语言分析泛化了,加入了列名的默认参数。现在再进一步:让用户可以传入灵活参数,也就是在本例中,用户想传入多少个列名都可以!

同样地,为了方便,pandas 已经以 pd 导入,文件 'tweets.csv' 已读入为 DataFrame tweets_df。您之前代码的一些部分也已提供。

本练习是课程的一部分

Python 函数入门

查看课程

练习说明

  • 补全函数头,提供 DataFrame df 的参数以及可变参数 *args
  • 在函数定义中补全 for 循环,使其遍历元组 args
  • 以 DataFrame tweets_df 和列名 'lang' 调用 count_entries(),将结果赋给 result1
  • 以 DataFrame tweets_df 和列名 'lang''source' 调用 count_entries(),将结果赋给 result2

交互式实操练习

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

# Define count_entries()
def ____(____, ____):
    """Return a dictionary with counts of
    occurrences as value for each key."""
    
    #Initialize an empty dictionary: cols_count
    cols_count = {}
    
    # Iterate over column names in args
    for col_name in ____:
    
        # 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
result1 = count_entries(____, ____)

# Call count_entries(): result2
result2 = count_entries(____, ____, ____)

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