Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- deep learning
- ASAC5기
- YouTube
- BFS
- cnn optuna
- ASAC
- sql eda
- join
- 데이터분석
- CCP자격증
- EDA
- 백준
- DFS
- Machine learning
- pandas
- ML
- selenium
- Shorts
- 뷰티 광고
- 파이썬 이미지 처리
- Python
- 크롤링
- 머신러닝
- 프로그래머스
- 파이썬
- JSON
- text summarization
- Crawling
- ASAC14일차
- SQL
Archives
- Today
- Total
낼름낼름 동동이
[ASAC 0702] WWH_Yelp EDA 1차 본문
7월 2일의 기록
기업연계 프로젝트로 진행하고 있는 yelp 리뷰 데이터 요약을 위해 데이터 탐색을 진행하였다. 시작 단계에서 헤매긴 했지만, 캐글에서 이전에 사람들이 많이 진행했던 방법이 있어서 이를 참조하면서 내용을 진행해보았다.
목차
- Yelp란?
- EDA
Yelp란?
2004년 7월에 설립된 미국의 종합 평점 플랫폼 운영사이다. 미국을 중심으로 식당이나 배달등 로컬 기반의 평점을 비롯한 서비스를 제공하고 있다. (맛집을 찾기에 유용하다) 한국으로 따지면 배민, 네이버 지도, 카카오 맵등의 기능을 종합적으로 제공하는 곳이라고 생각할 수 있다.
Yelp에는 맛집을 탐방했던 유저들이 남겨둔 후기들이 많이 모여있는데, 이 데이터가 오픈 되어 있다.
EDA
0. 라이브러리 및 함수
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from scipy import stats
import statsmodels.api as sm
import statsmodels.formula.api as smf
import ydata_profiling
### 워드 클라우드 -> 시각화
from wordcloud import WordCloud, STOPWORDS
1. 데이터 불러오기
# Tar 형식의 압축 파일 풀기
import os
import tarfile
tar_file = '/content/drive/MyDrive/ASAC 데이터 분석 과정/기업연계_프로젝트/yelp_dataset.tar'
# 파일 해제
if tarfile.is_tarfile(tar_file):
with tarfile.open(tar_file) as tar:
tar.extractall()
print(f"{tar_file} 파일이 성공적으로 해제되었습니다.")
else:
print(f"{tar_file} 파일은 tar 형식이 아닙니다.")
1-1. 압축 파일을 풀면 5개의 Json 파일이 존재
- Business.json - 레스토랑의 위치, 카테고리 및 등급 등 레스토랑 데이터
- Review.json - 실제 리뷰 데이터
- User.json - 리뷰를 남긴 유저의 데이터
- Checkin.json - 업무 시간 및 해당 시간에 들어오는 인원 수 데이터
- Tip.json - 짧은 리뷰 데이터
1-2. 판다스 DataFrame 정제
- 5개의 json 파일을 각각 불러오면서 저장하려고 하는데, review의 경우 699만개라서 pandas에서 그대로 불러오면 문제가 생겨서 chunksize를 70만으로 고정해서 10%만 사용하였다.
## 리뷰 699만개
import pandas as pd
# Load the JSON file into a DataFrame with a specified encoding
reviews = pd.read_json('/content/yelp_academic_dataset_review.json',\\
lines=True, orient='columns', chunksize=700000)
business = pd.read_json('/content/yelp_academic_dataset_business.json',\\
lines=True, orient='columns',chunksize=1500000)
checkins = pd.read_json('/content/yelp_academic_dataset_checkin.json',\\
lines=True, orient='columns',encoding="utf-8",chunksize=1500000)
users = pd.read_json('/content/yelp_academic_dataset_user.json',\\
lines=True, orient='columns',chunksize=1500000)
tips = pd.read_json('/content/yelp_academic_dataset_tip.json',\\
lines=True, orient='columns',chunksize=1500000)
2. 어떤 지역의 리뷰가 몰려있을까?
# package imports
#basics
import numpy as np
import pandas as pd
#misc
import gc
import time
import warnings
#viz
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.gridspec as gridspec
import matplotlib.gridspec as gridspec
# graph viz
import plotly.offline as pyo
from plotly.graph_objs import *
import plotly.graph_objs as go
#map section
import imageio
import folium
import folium.plugins as plugins
from mpl_toolkits.basemap import Basemap
#settings
start_time=time.time()
color = sns.color_palette()
sns.set_style("dark")
warnings.filterwarnings("ignore")
pyo.init_notebook_mode()
%matplotlib inline
2-1. Business(가게 정보) BaseMap 활용해서 지도에 찍어보기
#basic basemap of the world
plt.figure(1, figsize=(15,6))
# use ortho projection for the globe type version
m1=Basemap(projection='ortho',lat_0=20,lon_0=-50)
# hex codes from google maps color pallete = <http://www.color-hex.com/color-palette/9261>
#add continents
m1.fillcontinents(color='#bbdaa4',lake_color='#4a80f5')
# add the oceans
m1.drawmapboundary(fill_color='#4a80f5')
# Draw the boundaries of the countires
m1.drawcountries(linewidth=0.1, color="black")
#Add the scatter points to indicate the locations of the businesses
mxy = m1(business["longitude"].tolist(), business["latitude"].tolist())
m1.scatter(mxy[0], mxy[1], s=3, c="orange", lw=3, alpha=1, zorder=5)
plt.title("World-wide Yelp Reviews")
plt.show()
### 미국 쪽 데이터만 계속 잡힘..
# 비즈니스 id 개수는 전부 다 가져왔는데, 미국만 보이는 걸로 봐선 미국 쪽 데이터만 있는듯
2-2. 북미 지역에서 더 구체적으로 확인
# 북미 지역 기준으로 더 디테일하게 그려보기
lon_min, lon_max = -132.714844, -59.589844
lat_min, lat_max = 13.976715,56.395664
#create the selector
idx_NA = (business["longitude"]>lon_min) &\\
(business["longitude"]<lon_max) &\\
(business["latitude"]>lat_min) &\\
(business["latitude"]<lat_max)
#apply the selector to subset
NA_business=business[idx_NA]
#initiate the figure
plt.figure(figsize=(12,6))
m2 = Basemap(projection='merc',
llcrnrlat=lat_min,
urcrnrlat=lat_max,
llcrnrlon=lon_min,
urcrnrlon=lon_max,
lat_ts=35,
resolution='i')
m2.fillcontinents(color='#191919',lake_color='#000000') # dark grey land, black lakes
m2.drawmapboundary(fill_color='#000000') # black background
m2.drawcountries(linewidth=0.1, color="w") # thin white line for country
# Plot the data
mxy = m2(NA_business["longitude"].tolist(), NA_business["latitude"].tolist())
m2.scatter(mxy[0], mxy[1], s=5, c="#1292db", lw=0, alpha=0.05, zorder=5)
plt.title("North America Region")
3. 미국에서 지역적으로 인기 있는 카테고리는 무엇일까?
- 카테고리는 , 으로 연결되어 있어서 이를 one-hot encoding 해야 각 id가 가지고 있는 카테고리를 같은 차원에서 비교할 수 있다.
- 또, 여기에 음식점 리뷰만을 정제해서 보기 위해서 Rest 라는 워드를 포함하는 음식점만 분리해서 보았다.
## 음식점 리뷰만 정제해서 보자.. 카테고리에서 Rest라는 걸 포함하고 있는건 다 가져오기
all_cities = subset_business[subset_business['categories'].str.contains('Rest.*')==True]
# 한 셀에 들어있는 카테고리에서 각 레스토랑이 속한 다양한 카테고리를 분석할 수 있도록 원-핫 인코딩을 사용
df_rest = pd.Series(all_cities['categories']).str.get_dummies(',')
#'Restaurants'와 'Food' 같은 공통적인 열을 제거하고, 중복되는 카테고리를 합산했음
df_rest.drop(["Restaurants", " Restaurants", "Food", " Food"], axis=1, inplace=True)
# 열 이름에서 공백 제거를 해서 저장시키기
df_rest.columns = df_rest.columns.str.lstrip()
# 열 이름이 동일한 경우 합치기
all_rest = df_rest.groupby(by=df_rest.columns, axis=1).sum()
3-1. 바비큐 집이 가장 많은 지역은?
- Top 3: 필라델피아(펜실베니아 주), 내쉬빌(테네시 주), 탬파 (플로리다 주)
# 도시 이름만 가져와서, group by로 활용
from_business = all_cities[['city']]
# 바비큐집이 가장 많은 곳이 어디지?
all_rest.join(from_business).groupby('city').sum()['Barbeque'].sort_values(ascending=False).head(10)
3-2. 버거집은 어떨까?
- Top 3: 인디애나폴리스(인디애나 주), 필라델피아(펜실베니아 주), 투손 (애리조나 주)
all_rest.join(from_business).groupby('city').sum()['Burgers'].sort_values(ascending=False).head(10)
# 버거 카테고리는 바비큐보다 3배나 많은 것을 확인
# 바비큐랑 다르게 버거는 인디애나폴리스에 제일 많다
3-3. Pub은 어떨까?
- Top 3 : 필라델피아(펜실베니아 주), 인디애나폴리스(인디애나 주), 세인트 루인스(미주리 주)
all_rest.join(from_business).groupby('city').sum()['Pubs'].sort_values(ascending=False).head(10)
# 바비큐, 버거, 맥주 둘다 많다고 나오는 쪽은 우선 가게가 많은 곳일 수 있겠다..
- 일반적으로 도시가 크고 등록된 가게가 많으면 카테고리 별로 보아도 1등이 유사하게 나타나는 것이 확인된다.
- 가장 많이 등장하는 필라델피아, 인디애나 폴리스, 세인트 루인스 이 3곳에 대해서 더 깊게 보기로 하였다.
3.4. 필라델피아에 가장 많은 카테고리는?
- 유흥 카테고리(Nightlife)가 가장 많다. + Bar도 많은 것으로 봤을 때 술집이나 클럽 같은 형태의 가게들이 가장 많이 존재하는 것을 확인할 수 있다.
- 버거는 11위 정도에 위치하는 것을 확인할 수 있다.
- 물론 카테고리는 중복되어 있을 수 있으니 이점은 감안해서 봐야한다.
# 가장 자주 나오던 3개의 도시의 이름을 지정
cities=['Philadelphia','Indianapolis','Tucson']
df_cities=[]
# 각 도시에 있는 가게만 따로 뽑아내서 전처리
for c in cities:
city = subset_business[subset_business['city']==c]
rest = city[city['categories'].str.contains('Rest.*')==True]
df = pd.Series(rest['categories']).str.get_dummies(',')
df.drop(["Restaurants", " Restaurants", "Food", " Food"], axis=1, inplace=True)
df.columns = df.columns.str.lstrip()
result = df.groupby(by=df.columns, axis=1).sum()
df_cities.append(result)
phila, india, tuc = df_cities[0], df_cities[1], df_cities[2]
## 그중 필라델피아만 뽑아서 보기
phi = pd.DataFrame(phila.sum().sort_values(ascending=False).head(20),columns=['counts'])
phi.reset_index(inplace=True)
phi.rename({'index':'name'}, axis=1, inplace=True)
phi
import warnings
warnings.filterwarnings("ignore")
fig, ax = plt.subplots(figsize=(12,12))
# Visualizing 20 most popular Categories in Phila Restaurants
phila.sum().sort_values(ascending=True).tail(20).plot(kind='barh', color='Darkcyan', ax=ax)
ax.set_title('Top Categories for Phila Restaurants', fontsize=25, pad=25.0)
ax.set_xlabel("Category counts", fontsize=18)
ax.set_ylabel("Restaurants names", fontsize=18)
plt.show()
오늘은 우선, 미국 특정 대도시에서 가장 많이 존재하는 카테고리에 대해서 알아보았다. 다음에는 각 리뷰들에 있는 정보가 각 부분에 얼마나 영향을 주는 부분이 되는지 회귀 분석도 함께 진행해보려 한다.
'데이터분석 > 프로젝트' 카테고리의 다른 글
[ASAC 0704] WWH3 : [논문 리뷰] TextRank (0) | 2024.07.08 |
---|---|
[ASAC 0703] 프롬프트 기반 게임 아트 생성AI 프로젝트 기획 (0) | 2024.07.03 |
[ASAC 0628] 우형_연계 프로젝트 시작 : GIT 설치 (0) | 2024.06.28 |
뷰티 쇼츠 광고 조회수 예측 3: 데이터 전처리 + 모델링 (2) | 2024.06.15 |
뷰티 쇼츠 광고 조회수 예측 2: 음원 데이터 수집 (0) | 2024.06.15 |