종합 실습 (2)
와, 이전 장에서 했던 Twitter 언어 분석을 확장해서, 이제는 열 이름에 대한 기본 인자까지 포함하도록 일반화하셨네요. 이번에는 한 단계 더 나아가, 사용자에게 유연한 인자(flexible argument)를 전달할 수 있도록 할 거예요. 즉, 이 경우 사용자가 원하는 만큼 많은 열 이름을 넘길 수 있게 만듭니다!
편의를 위해 pandas는 pd로 임포트되어 있고, 'tweets.csv' 파일은 DataFrame tweets_df로 불러와져 있어요. 이전에 작업한 코드의 일부도 함께 제공됩니다.
이 연습은 강의의 일부입니다
Python 함수 입문
연습 안내
- 함수 헤더를 완성해 DataFrame
df매개변수와 가변 인자*args를 포함하세요. - 함수 정의 안의
for루프를 완성해, 루프가 튜플args를 순회하도록 하세요. - DataFrame
tweets_df와 열 이름'lang'을 전달해count_entries()를 호출하고, 결과를result1에 할당하세요. - DataFrame
tweets_df와 열 이름'lang','source'를 전달해count_entries()를 호출하고, 결과를result2에 할당하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Define count_entries()
def ____(____, ____):
"""Return a dictionary with counts of
occurrences as value for each key."""
#Initialize an empty dictionary: cols_count
cols_count = {}
# Iterate over column names in args
for col_name in ____:
# 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 = count_entries(____, ____)
# Call count_entries(): result2
result2 = count_entries(____, ____, ____)
# Print result1 and result2
print(result1)
print(result2)