시작하기무료로 시작하기

모아 보기 (2)

함수를 호출할 때 실수하는 일은 흔합니다. 당신이 직접 만든 함수라도요. 하지만 걱정하지 마세요! 이 연습에서는 지난 장의 count_entries() 함수에 try-except 블록을 추가해 개선해 보겠습니다. 이렇게 하면 사용자가 count_entries() 함수를 호출하면서 DataFrame에 없는 열 이름을 제공할 때, 함수가 도움이 되는 메시지를 제공할 수 있습니다.

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

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

Python 함수 입문

강의 보기

연습 안내

  • 올바른 인수로 함수를 호출했을 때 DataFrame을 처리하고 결과 딕셔너리를 반환하도록 try 블록을 추가하세요.
  • 잘못 호출되었을 때 다음 오류 메시지를 표시하도록 except 블록을 추가하세요: 'The DataFrame does not have a ' + col_name + ' column.'.

실습형 인터랙티브 연습

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

# Define count_entries()
def count_entries(df, col_name='lang'):
    """Return a dictionary with counts of
    occurrences as value for each key."""

    # Initialize an empty dictionary: cols_count
    cols_count = {}

    # Add try block
    ____:
        # 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

    # Add except block
    ____:
        ____

# Call count_entries(): result1
result1 = count_entries(tweets_df, 'lang')

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