모두 종합하기 (2)
잘하셨어요! 이제 열의 항목을 순회하고, 언어 이름을 키로, 해당 언어의 트윗 개수를 값으로 하는 딕셔너리를 만드는 기능을 정의했어요.
이번 연습 문제에서는 이전 문제에서 개발한 기능을 함수로 정의하고, 함수 안에서 결과 딕셔너리를 반환한 뒤, 적절한 인수로 함수를 호출해 보겠습니다.
편의를 위해 pandas 패키지는 pd로 임포트되어 있고, 'tweets.csv' 파일은 tweets_df 변수로 불러와져 있어요.
이 연습은 강의의 일부입니다
Python 함수 입문
연습 안내
- 두 개의 매개변수를 갖는 함수
count_entries()를 정의하세요. 첫 번째 매개변수df는 DataFrame이고, 두 번째 매개변수col_name은 열 이름입니다. for루프의if-else문 본문을 완성하세요: 키가 딕셔너리langs_count에 있으면 현재 값에1을 더하고, 그렇지 않으면 키를langs_count에 추가하고 값을1로 설정하세요. 코드에서는 루프 변수entry를 사용하세요.count_entries()함수 내부에서langs_count딕셔너리를 반환하세요.count_entries()함수를tweets_df와 열 이름'lang'을 인수로 전달하여 호출하세요. 호출 결과를 변수result에 할당하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Define count_entries()
def ____(____, ____):
"""Return a dictionary with counts of
occurrences as value for each key."""
# Initialize an empty dictionary: langs_count
langs_count = {}
# Extract column from DataFrame: col
col = df[col_name]
# Iterate over lang column in DataFrame
for entry in col:
# If the language is in langs_count, add 1
if entry in langs_count.keys():
____
# Else add the language to langs_count, set the value to 1
else:
____
# Return the langs_count dictionary
# Call count_entries(): result
# Print the result
print(result)