TIL_스파르타_데이터 분석 캠프 10기_유호빈 (2025.09.25)

유호빈·2025년 9월 25일

Data분석_10기

목록 보기
4/74

비가온다.
우중충하다.
이 때의 김치전은 못참는다.
그래서 점심에 김치전을 해먹었다.
맛있었다.
좋다.
공부하기 딱 좋은 컨디션을 김치전이 만들어줬다.
좋다.

1. 오늘 학습 키워드

오늘은 SQL 3-1~8 수강, python 1-15~1-18 수강을 하였다.
SQL은 case, if를 이용한 조건문 작성, python은 다양한 함수 (lambda, map, filter등)을 이용해서 값을 내는 과정을 배웠다.

2. 오늘 학습 한 내용을 나만의 언어로 정리하기

먼저 SQL부터 해보자.
SQL은 조건문을 좀 더 배워보았다. case, if를 이용해서 다양한 조건으로 정리가 가능하다.

select restaurant_name,
       price/quantity "단가",
       cuisine_type,
       order_id,
       case when (price/quantity <5000) and cuisine_type='Korean' then '한식1'
            when (price/quantity between 5000 and 15000) and cuisine_type='Korean' then '한식2'
            when (price/quantity > 15000) and cuisine_type='Korean' then '한식3'
            when (price/quantity <5000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식1'
            when (price/quantity between 5000 and 15000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식2'
            when (price/quantity > 15000) and cuisine_type in ('Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '아시아식3'
            when (price/quantity <5000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타1'
            when (price/quantity between 5000 and 15000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타2'
            when (price/quantity > 15000) and cuisine_type not in ('Korean', 'Japanese', 'Chinese', 'Thai', 'Vietnamese', 'Indian') then '기타3' end "식당 그룹"
from food_orders

조건문을 최대한 활용한 케이스의 코드다. 복잡해 보이지만 많은 함수를 사용하지 않고서도 이렇게 분류를 많이 할 수 있다는 것을 알 수 있다.

select case when delivery_time>30 then price*0.1*if(addr like '%서울%', 1.1, 1)
            when delivery_time>25 then price*0.05*if(addr like '%서울%', 1.1, 1)
            else 0 end "수수료",
            restaurant_name,
            order_id,
            price,
            delivery_time,
            addr
from food_orders

조건문을 이용해서 수수료를 부과하는 코드도 작성해보았다.

--숫자로 변경
cast(if(rating='Not given', '1', rating) as decimal) 

--문자로 변경
concat(restaurant_name, '-', cast(order_id as char))

그리고 가끔 avg, substring 함수를 사용했더니 data type이 다를 때 연산이 되지 않는 경우가 있는데, 위 코드를 이용해서 숫자, 문자로 변경해서 연산이 가능토록 할 수 있다.

select order_id,
       restaurant_name,
       day_of_the_week,
       delivery_time,
       case when day_of_the_week='Weekend' and delivery_time>=30 then 'Late'
            else if(day_of_the_week='Weekday' and delivery_time>=25, 'Late', 'On-time')
            end as "지연 여부"
from food_orders

이 코드는 실습 문제였고, case를 쓸지 if를 쓸지 고민을 한 다음에 작성해야 하는 코드였다.

그리고 python을 보자.

python은 좀 더 간결하게 작성하는 방법과,
map, filter, lambda식을 이용한 코드들을 작성해보았다.

num = 3

if num % 2 == 0:
    result = ('짝수')
else:
    result = '홀수'

result = ('짝수' if num % 2 == 0 else '홀수') #위에 꺼랑 똑같은 건데, 한줄로 깔끔하게 정리한거다.

print(f'{num}은 {result}입니다.')

#for문
a_list  = [1, 3, 2, 5, 1, 2]
# 배운 방식
b_list = []

for a in a_list:
    b_list.append(a*2)

#새로운 방식
b_list = [a*2 for a in a_list]

print(b_list)

if문을 보게 되면 조건에 따라 다른 값을 변수에 저장하고자 하는데,
고치기 전에는 여러줄에 나누어서 적었는데,
result = ('짝수' if num % 2 == 0 else '홀수')로 하여금 한줄에 보기 쉽게 작성을 할 수 있다.

for문은 기존 배운 방식에서는 모든 수를 하나씩 불러와서 계산을 하였지만,
새로운 방식으로도 크게 빗나가지는 않지만, 한줄로 쉽게 표현할 수 있음을 알 수 있다.

3. 학습하며 겪었던 문제점 & 에러

select order_id,
       restaurant_name,
       day_of_the_week,
       delivery_time,
       case when day_of_the_week='Weekend' and delivery_time>=30 then 'Late'
            else if(day_of_the_week='Weekday' and delivery_time>=25, 'Late', 'On-time')
            end as "지연 여부"
from food_orders

이 코드에서 내가 했갈렸던건, case와 if를 동시에 사용해서 처음에 제대로 조건을 분리하지 않은 탓에 실행 오류가 생겼었다.

그렇기에 else if를 넣어서 조건을 확실하게 분리하였고, 실행 결과 결과물 예시와 똑같이 나왔다.

#map, lambda
people = [
    {'name': 'bob', 'age': 20},
    {'name': 'carry', 'age': 38},
    {'name': 'john', 'age': 7},
    {'name': 'smith', 'age': 17},
    {'name': 'ben', 'age': 27},
    {'name': 'bobby', 'age': 57},
    {'name': 'red', 'age': 32},
    {'name': 'queen', 'age': 25}
]
#1차 작성
def check_adult(person):
    if person['age'] > 20:
        return'성인'
    else:
        return'청소년'

result = map(check_adult, people)
print(list(result))

#2차 작성
def check_adult(person):
    return('성인' if person['age'] > 20 else '청소년')
result = map(check_adult, people)
print(list(result))

#3차 작성
result = map(lambda person: ('성인' if person['age'] > 20 else '청소년'), people)
print(list(result))

map, lambda를 이용해서 간결하게 코드를 작성할 수 있는 방법을 배웠는데,
지금은 크게 이해를 못하겠다... 다시 한번 코드 작성 및 강의 보면서 이게 어떤 원리로 줄여갈 수 있는지에 대해 알아가봐야겠다.

#filter

result = filter(lambda person: person['age'] > 20, people)

print(list(result))

filter는 map이랑 유사하다고 하는데, 이것도 솔직히 잘 모르겠다... 강의 다시 듣자.

4. 내일 학습 할 것은 무엇인지

SQL은 솔직히 크게 막히는 것이 없다. 순조롭게 흘러가고 있다.
근데 python이 조금씩 헷갈린다. 최대한 반복을 해서 머리가 이해하도록 해야겠다.

내일은 SQL chapter4, python map, lambda, filter강의 다시 복습을 할 예정이다.

그리고 SQLD 시험도 약 1달 반 남은걸로 알고있는데, 공부 시작해야겠다.
추가적으로 위산기 실기도 준비해야지... 화이팅 11월 2일날 시험이니 빡시게 하자.

profile
데이터 분석을 하고 싶은 화공쟁이

0개의 댓글