ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python 데이터분석 기초 20 - 자전거 공유 시스템 시각화(web에서 데이터 가져옴), null 값이 있는 지에 대한 시각화, 칼럼 추가
    Python 데이터 분석 2022. 11. 2. 13:24

     

    # 자전거 공유 시스템 분석용
    #  : kaggle 사이트의 Bike Sharing in Washington D.C. Dataset를 편의상 조금 변경한 dataset을 사용함
    #
    # columns : 
    #  'datetime', 
    #  'season'(사계절:1,2,3,4), 
    #  'holiday'(공휴일(1)과 평일(0)), 
    #  'workingday'(근무일(1)과 비근무일(0)), 
    #  'weather'(4종류:Clear(1), Mist(2), Snow or Rain(3), Heavy Rain(4)), 
    #  'temp'(섭씨온도), 'atemp'(체감온도), 
    #  'humidity'(습도), 'windspeed'(풍속), 
    #  'casual'(비회원 대여량), 'registered'(회원 대여량), 
    #  'count'(총대여량)
    
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    plt.rc('font', family = 'malgun gothic')
    plt.rcParams['axes.unicode_minus'] =False
    
    train = pd.read_csv("https://raw.githubusercontent.com/pykwon/python/master/data/train.csv",
                        parse_dates = ['datetime'])
    print(train.head(3))
    print(train.shape)   # 표 작성
    print(train.columns) # 컬럼명 호출
    print(train.info())  # 구조 호출
    
    print(train.temp.describe()) # 데이터 요약 호출
    print(train.isnull().sum())  # null 값이 있는지 여부 확인
    
    # null이 포함된 카럼 확인용 시각화
    # pip install missingno
    import missingno as msno
    msno.matrix(train, figsize=(12, 5))
    plt.show()
    
    # 연월일 시분초를 별도 칼럼으로 추가
    train['year'] = train['datetime'].dt.year
    train['month'] = train['datetime'].dt.month
    train['day'] = train['datetime'].dt.day
    train['hour'] = train['datetime'].dt.hour
    train['minute'] = train['datetime'].dt.minute
    train['second'] = train['datetime'].dt.second
    print(train.head(2))
    print(train.columns)
    
    # 대여랑 시각화
    figure, (ax1, ax2, ax3, ax4) = plt.subplots(nrows = 1, ncols = 4)
    figure.set_size_inches(15, 5)
    
    sns.barplot(data = train, x = 'year', y = 'count', ax = ax1)
    sns.barplot(data = train, x = 'month', y = 'count', ax = ax2)
    sns.barplot(data = train, x = 'day', y = 'count', ax = ax3)
    sns.barplot(data = train, x = 'hour', y = 'count', ax = ax4)
    
    ax1.set(ylabel = 'Count', title = '연도별 대여량')
    ax2.set(ylabel = 'month', title = '월별 대여량')
    ax3.set(ylabel = 'day', title = '일별 대여량')
    ax4.set(ylabel = 'hour', title = '시간별 대여량')
    
    plt.show()
    
    # 대여량 시각화 boxplot
    figure, axes = plt.subplots(nrows=2, ncols=2)
    figure.set_size_inches(12, 8)
    
    sns.boxplot(data=train, y= 'count', orient='v', ax = axes[0][0])
    sns.boxplot(data=train, y= 'count', x='season', orient='v', ax = axes[0][1])
    sns.boxplot(data=train, y= 'count', x='hour', orient='v', ax = axes[1][0])
    sns.boxplot(data=train, y= 'count', x='workingday', orient='v', ax = axes[1][1])
    axes[0][0].set(ylabel='대여량', title='대여량')
    axes[0][1].set(xlabel='계절별', title='대여량', label='계절별 대여량')
    axes[1][0].set(xlabel='시간별', title='대여량', label='시간별 대여량')
    axes[1][1].set(xlabel='근무여부별', title='대여량', label='근무여부별 대여량')
    plt.show()
    
    # 산범도의 일종으로 rugplot - temp, windspeed, humidity
    fig, (ax1, ax2, ax3) = plt.subplots(ncols=3)
    fig.set_size_inches(15, 5)
    
    sns.rugplot(x = 'temp', y = 'count', data = train, ax = ax1)
    sns.rugplot(x = 'windspeed', y = 'count', data = train, ax = ax2)
    sns.rugplot(x = 'humidity', y = 'count', data = train, ax = ax3)
    plt.show()
    
    <console>
                 datetime  season  holiday  ...  casual  registered  count
    0 2011-01-01 00:00:00       1        0  ...       3          13     16
    1 2011-01-01 01:00:00       1        0  ...       8          32     40
    2 2011-01-01 02:00:00       1        0  ...       5          27     32
    
    [3 rows x 12 columns]
    (10886, 12)
    Index(['datetime', 'season', 'holiday', 'workingday', 'weather', 'temp',
           'atemp', 'humidity', 'windspeed', 'casual', 'registered', 'count'],
          dtype='object')
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 10886 entries, 0 to 10885
    Data columns (total 12 columns):
     #   Column      Non-Null Count  Dtype         
    ---  ------      --------------  -----         
     0   datetime    10886 non-null  datetime64[ns]
     1   season      10886 non-null  int64         
     2   holiday     10886 non-null  int64         
     3   workingday  10886 non-null  int64         
     4   weather     10886 non-null  int64         
     5   temp        10886 non-null  float64       
     6   atemp       10886 non-null  float64       
     7   humidity    10886 non-null  int64         
     8   windspeed   10886 non-null  float64       
     9   casual      10886 non-null  int64         
     10  registered  10886 non-null  int64         
     11  count       10886 non-null  int64         
    dtypes: datetime64[ns](1), float64(3), int64(8)
    memory usage: 1020.7 KB
    None
    count    10886.00000
    mean        20.23086
    std          7.79159
    min          0.82000
    25%         13.94000
    50%         20.50000
    75%         26.24000
    max         41.00000
    Name: temp, dtype: float64
    datetime      0
    season        0
    holiday       0
    workingday    0
    weather       0
    temp          0
    atemp         0
    humidity      0
    windspeed     0
    casual        0
    registered    0
    count         0
    dtype: int64
                 datetime  season  holiday  workingday  ...  day  hour  minute  second
    0 2011-01-01 00:00:00       1        0           0  ...    1     0       0       0
    1 2011-01-01 01:00:00       1        0           0  ...    1     1       0       0
    
    [2 rows x 18 columns]
    Index(['datetime', 'season', 'holiday', 'workingday', 'weather', 'temp',
           'atemp', 'humidity', 'windspeed', 'casual', 'registered', 'count',
           'year', 'month', 'day', 'hour', 'minute', 'second'],
          dtype='object')

     

     

    null 값이 있는지에 대한 시각화

     

     

    연도별, 월별, 일별, 시간별 데이터 시각화

     

    대여량, 계절별, 시간별, 근무여부별 boxplot 시각화

     

    temp, windspeed, humidity의 대여량을 rugplot 시각화

    댓글

Designed by Tistory.