Python 실습 | 베이직 라이브세션 QCC 3회차

2025. 1. 13. 16:17·Python

문제1

문자열을 입력 받아 각 단어가 몇 번 등장했는지 계산하는 word_frequency 함수를 작성하세요.

  • 조건: 빈 문자열 인 경우 "입력한 문자열이 없습니다."를 반환해주세요.
  • 힌트:
    • 문자열을 split() 메서드로 나눌 수 있습니다.
    • 딕셔너리를 사용해 단어 빈도를 계산하세요.
  • skeleton code
def word_frequency(text):
    """
    여기에 코드를 작성하세요.
    """

# 테스트 1
text1 = "hello world hello python world"
print(word_frequency(text1))  

# 테스트 2
text2 = ""
print(word_frequency(text2))
  • 출력 결과
'''
{'hello': 2, 'world': 2, 'python': 1}
입력한 문자열이 없습니다.
'''

`문제 풀이`

def word_frequency(text):
    if not text:
        print('입력한 문자열이 없습니다.')

    text_list = text.split()
    frequency = {}
    for i in text_list:
        if i in frequency:
            frequency[i] += 1
        else:
            frequency[i] = 1
    print(frequency)
            
text1 = "hello world hello python world"
word_frequency(text1)

`오답노트`

  • 딕셔너리 형태로 새로 만드는거 기억이 안나서 빈도 부분을 못 구했다
  • .split(' ') 안 하고 그냥 .split() 해도 됨
  • if text == '': 안 하고 그냥 if not text: 해도 됨

문제2

Seaborn 라이브러리에서 제공하는 Penguins 데이터셋을 활용하여 다음을 수행하세요:

  • 조건 1) 데이터 null값을 확인하고, 모든 칼럼에서 null값을 삭제하세요.
  • 조건 2) 선택된 데이터에서 species, sex, bill_length_mm, bill_depth_mm 열만 추출하세요.
  • 조건 3) species가 "Adelie"이면서 bill_length_mm이 40 이상이거나, species가 "Chinstrap"이면서 bill_length_mm이 30 이하인 데이터를 선택하세요.

final_result 데이터 프레임에 저장하고, shape을 출력하세요.

  • skeleton code
import seaborn as sns

# Penguins 데이터셋 로드
penguins = sns.load_dataset("penguins")

'''
여기에 코드를 작성하세요
'''

print(final_result.shape)
  • 출력 결과
'''
(50, 4)
'''

`문제 풀이`

import seaborn as sns

# Penguins 데이터셋 로드
penguins = sns.load_dataset("penguins")
penguins

# 조건1
penguins1 = penguins.dropna()

# 조건2
penguins2 = penguins1[['species', 'sex', 'bill_length_mm', 'bill_depth_mm']]

# 조건3
condition1 = (penguins2['species']== 'Adelie') & (penguins2['bill_length_mm'] >= 40)
condition2 = (penguins2['species']=='Chinstrap') & (penguins2['bill_length_mm'] <= 30)
final_result = penguins2[condition1|condition2]

print(final_result.shape)

`오답노트`

  • 틀린 건 아니지만, 매번 새로운 변수(ex.penguins1,2)에 안 담고 inplace=True로 해도 됨
'Python' 카테고리의 다른 글
  • 통계 공부 | 파이썬으로 정규분포, 이항분포 시각화(matplotlib subplot)
  • Python 실습 | 데이터프레임 합치기(merge,concat), 컬럼명 변경(rename), 인덱스 재지정(reset_index), 집계(agg, mean, sum 등)
  • 통계 공부 | 가설검정의 주의점
  • 통계 공부 | 상관관계, 파이썬으로 구하는 방법
초담
초담
4년차 마케터입니다
  • 초담
    그로스마케터의 기록
    초담
  • 전체
    오늘
    어제
  • 글쓰기 관리
    • 분류 전체보기 (117)
      • Data Analytics Project (3)
      • SQL (55)
      • Python (43)
      • GA4 (0)
      • Tableau (8)
      • 아티클 스터디 (7)
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
초담
Python 실습 | 베이직 라이브세션 QCC 3회차
상단으로

티스토리툴바