函数基础
关于基础部分,可以参考:
https://www.yuque.com/mugpeng/python/dr75i5
https://www.yuque.com/mugpeng/python/wqdvo0
第一个简单的函数
制作一个统计列表中元素出现个数的函数。
利用循环和字典的小特性。
# Define count_entries()def count_entries(df, col_name):"""Return a dictionary with counts ofoccurrences as value for each key."""# Initialize an empty dictionary: langs_countlangs_count = {}# Extract column from DataFrame: colcol = df[col_name]# Iterate over lang column in DataFramefor entry in col:# If the language is in langs_count, add 1if entry in langs_count.keys():langs_count[entry] += 1# Else add the language to langs_count, set the value to 1else:langs_count[entry] = 1# Return the langs_count dictionaryreturn langs_count# Call count_entries(): resultresult = count_entries(tweets_df, 'lang')# Print the resultprint(result)'''<script.py> output:{'en': 97, 'et': 1, 'und': 2}'''
