综合运用(1)
回想上一章的"综合运用"练习,您通过编写一个函数来统计特定语言的推文数量,做了一个简单的 Twitter 分析。该函数的输出是一个字典,以语言作为键(keys),以该语言的推文数量作为值(value)。
在本练习中,我们将把上一章的 Twitter 语言分析进行泛化。您将通过加入一个接收列名的默认参数来实现。
为方便起见,已将 pandas 以 pd 导入,并将 'tweets.csv' 文件读入到 DataFrame tweets_df 中。您之前编写代码的部分片段也已提供。
本练习是课程的一部分
Python 函数入门
练习说明
- 补全函数头,增加参数 DataFrame
df,以及用于指定 DataFrame 列名的参数col_name,其默认值为'lang'。 - 调用
count_entries(),传入 DataFrametweets_df和列名'lang'。将结果赋给result1。注意:由于'lang'是参数col_name的默认值,此处可以不显式指定。 - 调用
count_entries(),传入 DataFrametweets_df和列名'source'。将结果赋给result2。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define count_entries()
def count_entries(____, ____):
"""Return a dictionary with counts of
occurrences as value for each key."""
# 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
result1 = ____
# Call count_entries(): result2
result2 = ____
# Print result1 and result2
print(result1)
print(result2)