函数基础

关于基础部分,可以参考:
https://www.yuque.com/mugpeng/python/dr75i5
https://www.yuque.com/mugpeng/python/wqdvo0

第一个简单的函数

制作一个统计列表中元素出现个数的函数。

利用循环和字典的小特性。

  1. # Define count_entries()
  2. def count_entries(df, col_name):
  3. """Return a dictionary with counts of
  4. occurrences as value for each key."""
  5. # Initialize an empty dictionary: langs_count
  6. langs_count = {}
  7. # Extract column from DataFrame: col
  8. col = df[col_name]
  9. # Iterate over lang column in DataFrame
  10. for entry in col:
  11. # If the language is in langs_count, add 1
  12. if entry in langs_count.keys():
  13. langs_count[entry] += 1
  14. # Else add the language to langs_count, set the value to 1
  15. else:
  16. langs_count[entry] = 1
  17. # Return the langs_count dictionary
  18. return langs_count
  19. # Call count_entries(): result
  20. result = count_entries(tweets_df, 'lang')
  21. # Print the result
  22. print(result)
  23. '''
  24. <script.py> output:
  25. {'en': 97, 'et': 1, 'und': 2}
  26. '''