#!/usr/bin/env python # coding: utf-8 # # 투빅스 15기 정규세션 Week1 EDA - 15기 강지우 # In[7]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import warnings warnings.filterwarnings(action='ignore') get_ipython().run_line_magic('matplotlib', 'inline') plt.style.use('seaborn') plt.rc('font', family='Malgun Gothic') plt.rc('axes', unicode_minus=False) # ## 1. 데이터 불러오기 # #### 데이터 설명 # ##### datetime: # hourly date + timestamp 날짜+시간 # # ##### season: # 1 = spring, 2 = summer, 3 = fall, 4 = winter 봄/여름/가을/겨울 # # ##### holiday: # whether the day is considered a holiday 공휴일 # # ##### workingday: # whether the day is neither a weekend nor holiday 주중&공휴일x # # ##### weather: # 1: Clear, Few clouds, Partly cloudy, Partly cloudy 맑음 # # 2: Mist + Cloudy, Mist + Broken clouds, Mist + Few clouds, Mist 안개 # # 3: Light Snow, Light Rain + Thunderstorm + Scattered clouds, Light Rain + Scattered # clouds 적은 강수량 # # 4: Heavy Rain + Ice Pallets + Thunderstorm + Mist, Snow + Fog 높은 강수량 # # ##### temp: # temperature in Celsius 온도 # # ##### atemp: # --"feels like" temperature in Celsius 체감온도 # # ##### humidity: # relative humidity 습도 # # ##### windspeed: # wind speed 풍속 # # ##### casual: # number of non registered user rentals initiated 비회원 렌탈 수 # # ##### registered: # number of registered user rentals initiated 회원 렌탈 수 # # ##### count: # number of total rentals 총 렌탈 수 = 비회원 렌탈 수 + 회원 렌탈 수 # In[10]: dat = pd.read_csv('과제데이터.csv', encoding='UTF8') # In[11]: dat.info() # In[12]: print(str(10886/24)+'일의 데이터') #start date print(dat.iloc[0,0]) #end date print(dat.iloc[-1,0]) # In[13]: dat.describe() # In[14]: print('data shape: {}'.format(dat.shape)) # ### 가설 # 계절별로 렌탈수 차이 있을 것이다. # # 비오는 날에 렌탈 수가 적을 것이다. # # 풍속이 세면 렌탈 수가 적을 것이다. # # 주말에 렌탈 수가 더 많을 것이다. # # 온도가 극히 낮고 높은 날에 렌탈 수가 적을 것이다. # # 출퇴근 시간에 렌탈 수가 많을 것이다. # ## 2. 데이터 # ## Target Variable = count # In[15]: dat.head() # ### 범주형 변수 분석 # In[16]: print('season: {}'.format(len(np.unique(dat.season)))) print('weather: {}'.format(len(np.unique(dat.weather)))) print('holiday: {}'.format(len(np.unique(dat.holiday)))) print('workingday: {}'.format(len(np.unique(dat.workingday)))) # Variable|Unique|Explanation # :-|:-|:- # season|4|계절 # weather|4|날씨 4단계 # holiday|2|공휴일 0 or 1 # workingday|2|공휴일x 주말x 0 or 1 # ### 결측치 확인 # In[17]: dat.isnull().sum() # ### 수치형 변수 이상치 분석 # In[18]: num_att = ['temp', 'atemp', 'humidity', 'windspeed', 'casual', 'registered', 'count'] dat[num_att].describe() # In[19]: dat[num_att].hist(bins=30, figsize=(20,20)) plt.suptitle('outlier 제거 전 연속형 변수 히스토그램', fontsize=20) # In[20]: sns.pairplot(dat[num_att]) # 하루에 데이터가 24개씩 존재. 파악하기 힘들다. # 24개씩 묶은 데이터 생성 # ### 시간별 데이터 -> 일별 데이터 # In[21]: dat_group_by_day = dat dat_group_by_day['datetime'] = pd.to_datetime(dat_group_by_day['datetime'], format='%Y-%m-%d %H:%M:%S', errors='raise') # In[22]: dat_group_by_day.index = dat_group_by_day['datetime'] # In[23]: dat_group_by_day_ = dat_group_by_day.groupby(pd.Grouper(freq='D'))[dat.columns].mean() # 일별데이터 hist # In[24]: dat_group_by_day_[num_att].hist(bins=30, figsize=(20,20)) # 일별데이터 pair plot # In[25]: sns.pairplot(dat_group_by_day_[num_att]) # In[26]: dat[num_att].corr() # In[27]: sns.heatmap(dat[num_att].corr(),cmap='YlGnBu', annot=True) plt.show() # temp와 atemp는 선형적인 관계가 아니다. # 기온이 극히 높은 경우/ 낮은 경우일 때를 나타낼 수 있는 변수를 추가 # ### temp와 atemp의 파생변수 생성 # temp와 atemp 분포파악 후 파생변수 생성 기준점 결정 # In[28]: sns.distplot(dat['temp'], kde=True, rug=True) # In[29]: sns.distplot(dat['atemp'], kde=True, rug=True) # In[30]: dat['temp'].mean() + 2*dat['temp'].std() # 고온/저온을 1.5시그마를 벗어나는 값으로 설정 # In[31]: dat['high_temp'] = 0 dat['low_temp'] = 0 dat['high_atemp'] = 0 dat['low_atemp'] = 0 dat.loc[dat['temp']>dat['temp'].mean() + 2*dat['temp'].std(), 'high_temp'] = 1 dat.loc[dat['temp']dat['atemp'].mean() + 2*dat['atemp'].std(), 'high_atemp'] = 1 dat.loc[dat['atemp']