데이터 분석/[Python] 프로젝트

[Kaggle] Airbnb New User Bookings - (1) 데이터확인

INCHELIN 2023. 3. 15. 16:44
728x90

 
Airbnb New User Bookings | Kaggle
2015년에 캐글에서 진행한 airbnb 프로젝트를 가지고 데이터 분석, 모델링하는 과정을 작성해보려고 한다.
 
[Overview]

  • 새로 가입한 유저가 처음 여행을 예약할 나라를 예측

[Dataset Description]

  • demographics, web session records, and some summary statistics
  • train_users.csv / test_users.csv
컬럼명 설명 예시
id 유저 ID gxn3p5htnn
data_account_created 가입일자 2010-06-28
timestamp_first_active 처음 활동 날짜 20090319043255
date_first_booking 첫 예약 날짜 NaN
gender 성별 unknown
age 나이 NaN
signup_method 가입 방법 facebook
signup_flow 사용자가 회원 가입한 페이지 0
language 선호하는 언어  en
affiliate_channel 유료 마케팅 종류 direct
affiliate_provider 마케팅이 진행된 곳(예:구글) direct
first_affiliate_tracked 회원 가입 전 사용자가 상호작용한 최초 마케팅 untracked
signup_app 회원가입한 애플리케이션 Web
first_device_type 최초 기기 유형 Mac Desktop
first_browser 최초 브라우저 Chrome
country_destination 예측할 변수 NDF
  • Sessions.csv
컬럼명 설명 예시
user_id 유저 ID d1mm9tcy42
action 활동명(예:show,search 등) lookup
action_type 활동 타입(예:view, click 등) NaN
action_detail 활동 상세 NaN
device_type 기기 유형 Windows Desktop
secs_elapsed 세션 시간(단위 :초) 319.0
  • countries.csv (첫 예약 국가의 통계 요약)
컬럼명 설명 예시
country_destination 도착지 국가 AU
lat_destination 도착지 위도  -26.853388
lng_destination 도착지 경도 133.275160
distnace_km 도착지까지 거리(km) 15297.7440
destination_km2 도착지 면적(km2) 7741220.0
destination_language 도착지 언어 eng
language_levenshtein_distance 언어 간의 편집거리 0.00
  • age_gender_bkts.csv (유저의 연령대, 성별, 국가에 따른 통계 요약)
컬럼명 설명 예시
age_bucket 연령대 100+
country_destination 도착지 국가 AU
gender 성별 male
population_in_thousands 인구(단위 : 천 명) 1
year 연도 2015

이제는 본격적으로 각 데이터들을 불러오고, 변수들에 대한 탐색을 해보겠습니다.

(가설1) 사용하는 언어에 따라 예약하는 국가가 다를 것이다 (예: 영어를 사용하는 회원은 영어권 국가 예약을 더 많이 할 것이다)
(가설2) 연령별or성별에 따라 예약하는 국가가 다를 것이다 (예: 20대 여성과 50대 남성의 예약하는 국가가 다를 것이다)
(가설3) 그냥 가까운 거리의 국가로 많이 예약한다 

import pandas as pd
import datetime
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

train_user.shape # (213451, 16)
train_user.head()

train_user.isnull().sum()

총 2만명 가입자의 약 58%인 1만 2천명 정도가 가입만 하고 예약을 안 한 회원입니다. (전체회원 213,451명, 예약회원 124,543명)
 

  • 나이(age)
train_user['age'].describe()
# min : 1 / max : 2014 / null : 87990개

age의 outlier에 대한 처리가 필요하다. 
미국에서 성인 나이가 18세부터라고 한다. 그리고 고령 나이는 100세 이상으로 잘랐다.

train_user.loc[train_user['age'] < 18 ] = np.nan
train_user.loc[train_user['age'] >= 100 ] = np.nan

다시 describe()로 통계치를 보면 평균 나이는 36세이다.

 

  • 성별(gender)
train_user['gender'].value_counts().plot(kind='bar')
# -unknown- / FEMALE / MALE / OTHER

train_user['gender'].replace('-unknown-',np.nan, inplace=True)
train_user['gender'].value_counts().plot(kind='bar')

 

  • 도착지 국가(country_destination)

미국유저 대상이라 그런지, 주로 미국(US)로 예약함
(* NDF : no destination found)

train_user['country_destination'].value_counts().plot(kind='bar')

  • 연령에 따른 도착지 국가 비교

65세 기준으로 성인과 노인으로 연령그룹을 나누었다.

65세 미만 성인이 노인보다 US미국을 더 선호하며, 노인의 경우 FR프랑스, IT이탈리아 국가를 더 선호한다.

adult = sum(train_user['age'] <= 64)
elderly = sum(train_user['age'] > 64)

adult_destinations = train_user.loc[train_user['age'] <=64, 'country_destination'].value_counts() / adult * 100
elderly_destinations = train_user.loc[train_user['age'] > 64, 'country_destination'].value_counts() / elderly * 100

# Bar width
width = 0.4

adult_destinations.plot(kind='bar', width=width, color='#87CEEB', position=0, label='Adult', rot=0)
elderly_destinations.plot(kind='bar', width=width, color='#FFA35D', position=1, label='Elderly', rot=0)

plt.legend()
plt.xlabel('Destination Country')
plt.ylabel('Percentage')

sns.despine()
plt.show()

  • 성별에 따른 도착지 국가 비교

성별에 따른 도착지 국가의 차이가 뚜렷하게 없음

women = sum(train_user['gender'] == 'FEMALE')
men = sum(train_user['gender'] == 'MALE')

female_destinations = train_user.loc[train_user['gender'] == 'FEMALE', 'country_destination'].value_counts() / women * 100
male_destinations = train_user.loc[train_user['gender'] == 'MALE', 'country_destination'].value_counts() / men * 100

# Bar width
width = 0.4

male_destinations.plot(kind='bar', width=width, color='#87CEEB', position=0, label='Male', rot=0)
female_destinations.plot(kind='bar', width=width, color='#FFA35D', position=1, label='Female', rot=0)

plt.legend()
plt.xlabel('Destination Country')
plt.ylabel('Percentage')

sns.despine()
plt.show()

 

  • 가입방법(signup_method)
train_user['signup_method'].value_counts().plot(kind='bar')

  • 가입 애플리케이션(signup_app)

미국이라 그런가 확실히 iOS유저가 많습니다.

train_user['signup_app'].value_counts().plot(kind='bar')

 

 

  • 최초 기기 유형(first_device_type)
train_user['first_device_type'].value_counts().plot(kind='bar')

  • 최초 브라우저(first_browser)
train_user['first_browser'].value_counts().head(10).plot(kind='bar') # top 10개

 

위에까지 정리해보자면, Web으로 가입한 유저가 많고 그래서 첫 브라우저가 chrome과 safari, firefox순으로 많습니다.
그리고 mac과 windows desktop 기기가 많구요.
이걸 교차분석해서 성별이나 연령대별로 볼 수 있을 것 같은데 생략하겠습니다.

 

날짜와 관련된 변수들에 대한 데이터타입 변경을 해줍니다.

train_user['date_account_created'] = pd.to_datetime(train_user['date_account_created'], format='%Y-%m-%d')
train_user['timestamp_first_active'] = pd.to_datetime(pd.to_datetime(train_user['timestamp_first_active'].astype(str), format='%Y%m%d%H%M%S').dt.strftime('%Y-%m-%d'))
train_user['date_first_booking'] = pd.to_datetime(train_user['date_first_booking'], format='%Y-%m-%d')

  • 계정 생성날짜(date_account_created)

2010년부터 2014년까지 가입하였고, 점차 가입율이 증가하는 추세

  • 첫 활동 날짜(timestamp_first_active)

가입날짜가 2010년부터인 반면 첫 활동 날짜가 2009년인 데이터가 소수있는데 이거는 잘못된 데이터인듯 합니다.

2012년 기점으로 점차 활동하는 유저가 많아지는데, 가입하는 유저가 많아져서 그런 것 같습니다. 비슷한 추세그래프임.

plt.figure(figsize =(10, 6))
train_user['timestamp_first_active'].value_counts().plot(kind='line', linewidth=1.2)

  • 첫 예약날짜(date_first_booking)

예약 날짜는 가입한 날짜 이후가 되겠고, 2014년 중순까지 꾸준히 예약을 하다가 꺾이는 추세입니다.

 

  • '첫 예약 날짜 - 가입 날짜'

'첫 예약 날짜 - 가입 날짜'의 평균은 45days입니다. 즉, 평균적으로 가입하고 약 45일 이후에 예약을 하게 됩니다

그러나 min값에 - days가 있는데 이런 데이터는 잘못된 것 같습니다. 

대부분은 가입하고 한 달 내에 예약을 합니다. 길게는 가입하고 약 1년뒤에 예약합니다.

(train_user['date_first_booking']-train_user['date_account_created']).describe()

sessions = pd.read_csv('sessions.csv')
sessions.head()

  • action

show, index, search_results 등 다양한 활동을 하고 show보는 행위를 가장 많이 한다.

sessions['action'].value_counts()

  • action_detail 세션시간

패스워드 설정 > 이메일 링크 확인 > 로그인 --> 주로 개인정보페이지

이외에도 리뷰페이지, 결제페이지, 호스트 연락 등의 action에서 많이 머무는 것을 알 수 있다.

a = sessions.groupby('action_detail')['secs_elapsed'].mean().sort_values(ascending=False)
a.head(10).plot(kind='bar')

  • 예약 회원과 비예약 회원의 평균 세션시간 차이

예약 회원은 평균 세션시간이 32646초 = 9시간 정도?

비예약 회원은 평균 세션시간 17741초 = 5시간 정도를 보인다.

train_user['booking'] = train_user['country_destination'].apply(lambda x: 0 if pd.isnull(x) else 1)

sessions_booking = sessions[sessions['user_id'].isin(train_user[train_user['booking']==1]['id'].tolist())].reset_index(drop=True)
sessions_X = sessions[sessions['user_id'].isin(train_user[train_user['booking']==0]['id'].tolist())].reset_index(drop=True)

sessions_booking.groupby('user_id')['secs_elapsed'].mean().mean() # 32646.05289939167
sessions_X['secs_elapsed'].mean() # 17741.76
  • 총 10개 국가에 대한 정보
countries = pd.read_csv('countries.csv')
countries.head(10)

 

  • destination_language(도착지 국가 언어)

영어를 사용하는 국가가 4곳이고 나머지는 모두 1곳씩

countries['destination_language '].value_counts().plot(kind='bar')

 

 

age_gender = pd.read_csv('age_gender_bkts.csv')
age_gender.head()

 

728x90