▷ 오늘 학습 계획: EDA 강의(웹데이터 5~6)
import pandas as pd from urllib.request import urlopen from bs4 import BeautifulSoup
url="https://movie.naver.com/movie/sdb/rank/movie.naver?sel=cur&date=20210914" response = urlopen(url) # response.status soup = BeautifulSoup(response, "html.parser") print(soup.prettify())
영화 제목 태그: "div" 태그 → "title" class → "a"태그
soup.find_all("div", "tit5") # soup.select(".tit5") # soup.select("div.tit5") len(soup.find_all("div", "tit5"))
soup.find_all("div", "tit5")[0].a.string soup.select(".tit5")[0].find("a").text soup.select(".tit5")[0].select_one("a").get_text()
영화 평점 태그: "td" 태그 → "point" class
soup.find_all("td", "point") # soup.select(".point") len(soup.find_all("td", "point"))
soup.find_all("td", class_="point")[0].text soup.select("td.point")[0].string
영화 제목 리스트
end = len(soup.find_all("div", "tit5")) movie_name = [] for n in range(0, end): movie_name.append( soup.find_all("div", "tit5")[n].a.string ) # list comprehension movie_name = [soup.select(".tit5")[n].a.text for n in range(0, end)]
영화 평점 리스트
end = len(soup.find_all("td", "point")) movie_point = [soup.find_all("td", "point")[n].string for n in range(0,end)]
전체 데이터 수 확인
len(movie_name), len(movie_point)
날짜만 변경하면 원하는 기간 만큼 데이터를 얻을 수 있다.
pandas의 date_range
date = pd.date_range("2021.01.01", periods=100, freq="D") date[0].strftime("%Y-%m-%d")
문자열 format
test_string = "Hi, I'm {name}" test_string.format(name="Zerobase")
반복문으로 원하는 기간의 데이터 가져오기
import time
from tqdm import tqdm
movie_date = []
movie_name = []
movie_point = []
for today in tqdm(date):
url = "https://movie.naver.com/movie/sdb/rank/movie.naver?sel=cur&date={date}"
response = urlopen(url.format(date=today.strftime("$Y$m$d")))
soup = BeautifulSoup(response, "html.parser")
end = len(soup.find_all("td", "point"))
movie_date.extend([today for _ in range(0,end)])
movie_name.extend([soup.select("div.tit5")[n].find("a").text for n in range(0,end)])
movie_point.enxtend([soup.find_all("td", "point")[n].string for n in range(0,end)])
time.sleep(0.5)
데이터 크기 확인하기
len(movie_date), len(movie_name), len(movie_point)
Pandas DataFrame
movie = pd.DataFrame({ "date" : movie_date, "title" : movie_name, "point" : movie_point })
astype
movie.info() # point 컬럼이 object형으로 되어 있음 movie["point"] = movie["point"].astype(float) # float로 형변환
데이터 저장
movie.to_csv("../data/03. naver_movie_data.csv", sep=",", encoding="utf-8")
import numpy as np import pandas as pd moivie = pd.read_csv("../data/03. naver_movie_data.csv", index_col=0)
pivot table
movie_unique = pd.pivot_table(data=movie, index="name", aggfunc=np.sum) movie_best = movie_unique.sort_values(by="point", ascending=False) movie_best.head(10) #상위 10개 movie_best.tail(10) #하위 10개
DataFrame의 검색 명령(query): 지정한 영화의 평점을 날짜별로 조회하기
tmp = movie.query("name ==['화양연화']") tmp
시각화: 날짜에 따른 평점의 변화
import matplotlib.pyplot as plt
from matplotlib import rc
rc("font", family = "Malgun Gothic")
%matplotlib inline
plt.figure(figsize = (20,8))
plt.plot(tmp["date"], tmp["point"])
# 선 그래프 x축 날짜, y축 평점(날짜에 따른 평점의 변화를 선그래프로 표현 - 시계열)
plt.title("날짜별 평점")
plt.xlabel("날짜")
plt.ylabel("평점")
plt.xticks(rotation="vertical") #날짜를 세로로
plt.legend(labels = ["평점 추이"], loc = "best")
plt.grid(True)
plt.show()
pivot table로 100일간의 영화 데이터 모두 정리하기
movie_pivot = pd.pivot_table(data=movie, index="data", columns="name", values="point") movie_pivot.head() # 컬럼 값이 mullti index → movid_pivot.columns = movie_pivot.columns.droplevel() # 엑셀파일로 저장 movie_pivot.to_excel("../data/03. movie_pivot.xlsx")
matplotlib 한글설정 방법 추가
import platform
import seaborn as sns
from matplotlib import font_manager, rc
path = "C:/Windows/Fonts/malgun.ttf"
if platform.system() == "Darwin":
rc("font", family="Arial Unicode Ms")
elif platform.system() == "Windows":
font_name = font_manager.FontProperties(fname=path).get_name()
rc("font", family = font_name)
else:
print("Unknown system. sorry")
영화 선정 후 그래프로 확인하기
target_col = ["범죄도시", "국가부도의 날", "신과함께-죄와 벌", "공범자들", "1987"] plt.figure(figsize = (20,8)) plt.title("날짜별 평점") plt.xlabel("날짜") plt.ylabel("평점") plt.xticks(rotation="vertical") plt.tick_params(bottom="off", labelbottom="off") plt.plot(movie_pivot[target_col]) plt.legend(target_col, loc="best") plt.grid(True) plt.show()
📝 네이버 영화 평점 사이트가 이번달부터 없어져서 작성된 코드 실행은 못했지만 강의 자료 보면서 이해할 수 있었다.
▷ 내일 학습 계획: EDA 강의(유가분석)