시작하기무료로 시작하기

모두 합쳐 보기 (3)

이전 연습 문제에서는 함수 count_entries()try-except 블록을 추가했어요. 이렇게 하면 사용자가 DataFrame에 없는 열 이름으로 count_entries()를 호출했을 때도 도움이 되는 메시지를 볼 수 있었죠. 이번에는 DataFrame에 없는 열 이름을 사용자가 제공하는 경우, 대신 ValueError를 발생시키도록 해 보겠습니다.

편의를 위해 pandaspd로 임포트되어 있고, 'tweets.csv' 파일은 DataFrame tweets_df로 불러와져 있어요. 이전에 작성한 코드의 일부도 제공됩니다.

이 연습은 강의의 일부입니다

Python 함수 입문

강의 보기

연습 안내

  • col_name이 DataFrame df의 열이 아니라면, ValueError 'The DataFrame does not have a ' + col_name + ' column.'를 발생시키세요.
  • 새로 만든 함수 count_entries()를 호출해 tweets_df'lang' 열을 분석하세요. 결과를 result1에 저장합니다.
  • result1을 출력하세요. 이 단계는 이미 완료되어 있으니 'Submit Answer'를 눌러 결과를 확인하세요. 다음 연습 문제에서 필요한 ValueError가 발생하는 것을 확인하게 됩니다.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Define count_entries()
def count_entries(df, col_name='lang'):
    """Return a dictionary with counts of
    occurrences as value for each key."""
    
    # Raise a ValueError if col_name is NOT in DataFrame
    if col_name not in df.columns:
        ____

    # 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
____

# Print result1
print(result1)
코드 편집 및 실행