문제 1. 데이터 조회, 정렬, 조건 필터
'''
[ 조건 ]
- 나이가 20살 이상 40살 미만인 승객
- pclass가 1등급 혹은 2등급인 승객
- 열(column)은 survived, pclass, age, fare 만 나오게 출력
- 10개만 출력
'''
# Skeleton code
import pandas as pd
import seaborn as sns
df = sns.load_dataset('titanic')
# 데이터 필터링: 나이, pclass 등급
df = df[(df['age'] >=20) & (df['age'] < 40)
& ((df['pclass'] == 1) | (df['pclass'] == 2))]
# survived, pclass, age, fare 컬럼만 출력
result_data = df[['survived', 'pclass', 'age', 'fare']].head(10).reset_index()
# 결과 데이터 조회
result_data
문제 2. 데이터 합치기 및 컬럼 생성
'''
[ 조건 ]
- **고객 테이블(customers)를 기준으로 주문 테이블(orders)를 합쳐주세요. 주문 금액이 없는 고객도 모두 포함되어야 합니다.**
- 주문 금액이 없는 경우, 0으로 표현
- 주문금액이 있는 경우 "구매", 주문금액이 0인 경우 "미구매"로 분류하는 "구매여부" 칼럼을 생성
- df출력 (결과칼럼: 고객번호, 이름, 금액, 구매여부)
'''
# Skeleton code
import pandas as pd
import numpy as np
#고객 테이블
customers = pd.DataFrame({
'고객번호': [1001, 1002, 1003, 1004, 1005, 1006, 1007],
'이름': ['승철', '동경', '예나', '혜연', '장훈', '채운', '다연']
})
#주문 테이블
orders = pd.DataFrame({
'cno': [1001, 1001, 1005, 1006, 1008, 1001],
'금액': [10000, 20000, 15000, 5000, 100000, 30000]
})
# 컬럼명 통일
orders = orders.rename(columns={"cno":"고객번호"})
# 데이터프레임 merge
df = pd.merge(customers, orders, on='고객번호', how='left')
# 고객번호 기준으로 금액 합치기
sum_price = df.groupby('고객번호')['금액'].sum()
# sum_price + 기존 데이터프레임 merge
df = pd.merge(df, sum_price, on='고객번호', how='inner')
# 필요한 칼럼만 추출
df = df[['고객번호', '이름', '금액_y']]
# 금액_y 이름 변경
df.rename(columns={"금액_y":"금액"}, inplace=True)
# 중복행 제거
df = df.drop_duplicates(keep='first', ignore_index=True)
# 구매여부 컬럼 추가
df['구매여부'] = np.where(df['금액']==0, '미구매', '구매')
df
문제 3. iris 데이터 활용
'''
[ 요구사항 ]
- 3-1) species별 sepal length, sepal width, petal length, petal width의 평균과 표준편차를 구하세요.**
- 3-2) sepal length, sepal_width, petal_length, petal_width 4가지 변수 중 가장 상관관계가 높은 두 변수를 찾으세요.**
- 3-3) 위에서 구한 두 변수를 x,y축으로 두고 species에 따라 분류하는 산점도를 생성하세요.**
'''
# Skeleton code
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
iris= sns.load_dataset("iris")
# 평균, 표준편차 구하기
iris_mean = iris.groupby('species').mean()
iris_std = iris.groupby('species').std()
# 상관계수 계산 - petal_width, petal_length가 가장 상관 관계가 높음
iris_corr = iris.corr(numeric_only=True)
# Scatter plot by Groups
sns.scatterplot(x='petal_length', y='petal_width', hue='species', style='species', data=iris)
문제 4. 삼성전자 주가 데이터 처리
# 2019-01-01 ~ 2024-12-16 데이터 불러오기
samsung = fdr.DataReader('005930', '2019-01-01', '2024-12-16')
# 인덱스를 컬럼으로 변경
samsung.reset_index(drop=False, col_fill='Date', inplace=True)
# Date에서 Month만 추출
samsung['Year'] = samsung['Date'].dt.year
samsung['Month'] = samsung['Date'].dt.month
samsung_mean = samsung.groupby(['Year','Month'])[['Close']].mean()
samsung_mean['전월대비(%)'] = round(samsung_mean['Close'].pct_change(periods=1),1)
samsung_mean['전년동월대비'] = round(samsung_mean['Close'].pct_change(periods=12),1)
samsung_mean
문제 5. 이상치 처리
'''
[ 요구 사항 ]
1) 전체 데이터 결측값 처리 (삭제)
2) Quantity, UnitPrice 0 이하 제거
3)상품코드가 일반적이지 않은 경우
- StockCode 중 다음과 같이 문자로만 구성된 경우는 일반적이지 않은 경우로 보고, 숫자를 한개이상 포함하지 않는 경우는 이상치로 정의, 데이터셋에서 제거
4) Quantity, UnitPrice 컬럼 IQR 기반 방법으로 이상치 제거**
- IQR (Inter Quantitle Range) = Q3 (3사분위 수) - Q1 (1사분위수)
- Quantity 컬럼과 UnitPrice컬럼에서, lower_bound (Q1 - 1.5 * IQR) 보다 작거나 upper_bound( Q3 + 1.5 * IQR) 보다 큰 경우를 이상치로 정의하고 제거
- 4단계까지 완성 후, df.shape를 출력**
'''
# Skeleton 코드
import pandas as pd
import re
import numpy as np
df = pd.read_csv('online_retail.csv', encoding="ISO-8859-1")
# 결측값 처리 (삭제)
df.dropna(axis=0, how='any', inplace=True)
# Quantity, UnitPrice 0 이하 제거
df.drop(df[(df['Quantity']<=0)|(df['UnitPrice']<=0)].index, inplace=True)
# 상품코드가 일반적이지 않은 경우
df.drop(df[~df['StockCode'].str.contains(r'\d+')].index, inplace=True)
# IQR 기반 이상치 제거 함수
def outlier(arr,data):
q1 = np.quantile(arr, 0.25)
q3 = np.quantile(arr, 0.75)
iqr = q3-q1
upper_bound = q3 + (1.5*iqr)
lower_bound = q1 - (1.5*iqr)
data.drop(data[(arr > upper_bound)|(arr < lower_bound)].index, inplace=True)
return data
# Quantity, UnitPrice 기준 이상치 제거
outlier(df['Quantity'],df)
outlier(df['UnitPrice'], df)
# df.shape 출력
df.shape