시작하기무료로 시작하기

문자열 패턴 추출하기

hiking 데이터세트의 Length 열은 문자열이지만, 그 안에는 하이킹 거리(마일)가 들어 있습니다. 정규 표현식을 사용해 이 마일 수를 추출한 다음, pandas에서 람다를 사용해 DataFrame 전체에 추출 로직을 적용해 보겠습니다.

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

Python으로 배우는 Machine Learning 전처리

강의 보기

연습 안내

  • length 인수의 텍스트에서 숫자와 소수를 찾도록 적절한 패턴으로 검색하세요.
  • 일치한 패턴을 추출해 float으로 변환하세요.
  • hiking["Length"] 열의 각 행에 return_mileage() 함수를 적용하세요.

실습형 인터랙티브 연습

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

# Write a pattern to extract numbers and decimals
def return_mileage(length):
    
    # Search the text for matches
    mile = re.____(____, ____)
    
    # If a value is returned, use group(0) to return the found value
    if mile is not None:
        return float(____)
        
# Apply the function to the Length column and take a look at both columns
hiking["Length_num"] = ____.apply(____)
print(hiking[["Length", "Length_num"]].head())
코드 편집 및 실행