모두 합쳐보기 (1)
이전 챕터의 ‘모두 합쳐보기’ 연습 문제에서, 특정 언어로 작성된 트윗 개수를 세는 함수를 만들어 간단한 Twitter 분석을 해 보셨죠. 그 함수의 출력은 언어를 키로, 해당 언어의 트윗 개수를 값으로 갖는 딕셔너리였습니다.
이번 연습에서는 이전 챕터에서 만든 Twitter 언어 분석을 일반화해 보겠습니다. 이를 위해 열 이름을 받는 기본 인자를 함수에 포함할 거예요.
편의를 위해 pandas는 pd로 임포트되어 있고, 'tweets.csv' 파일은 DataFrame tweets_df로 불러와져 있습니다. 이전에 작성하신 코드의 일부도 제공됩니다.
이 연습은 강의의 일부입니다
Python 함수 입문
연습 안내
- 함수 헤더를 완성하세요. DataFrame
df를 위한 매개변수와, DataFrame 열 이름을 위한 매개변수col_name(기본값은'lang')을 지정합니다. tweets_dfDataFrame과 열 이름'lang'을 전달해count_entries()를 호출하고, 결과를result1에 할당하세요. 참고로'lang'은col_name의 기본값이므로 여기서는 명시하지 않아도 됩니다.tweets_dfDataFrame과 열 이름'source'를 전달해count_entries()를 호출하고, 결과를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)