[스파르타]파이썬 데이터 분석 - 3주차(#wordcloud, pivot table, 히트맵)
새로 알게 된 내용😁
1. 데이터 인덱스명 변경하기
# user_id를 count로 변경
count = lecture.rename(columns = {'user_id':'count'})
2. wordcloud 만들기
많은 데이터 중 특정 키워드가 얼마나 많이 사용되는지 직관적으로 나타내주 것이다.
1) wordcloud 설치 후 라이브러리 불러오기
# wordcloud 설치
conda install -c conda-forge wordcloud
# wordcloud 라이브러리 불러오기
import numpy as np
from PIL import Image
from wordcloud import WordCloud
import matplotlib.pyplot as plt
2) 데이터 불러오기 - 글자 외 특수 문자 제외 처리
# utf-8로 인코딩해서 읽기모드로 데이터 불러오기
text = open('./data/mysong.txt', 'r', encoding='utf-8-sig')
# 개행문자를 띄어스기로 대체하기
result = text.read().replace('\n', " ")
# 데이터에서 특수 기호 제거하기
import re
pattern = '[^\w\s]'
text = re.sub(pattern=pattern, repl='', string=result)
3) 데이터 한글 설정하기
# 데이터 한글 설정하기
import matplotlib.font_manager as fm
# "Gothic" 들어간 폰트 경로 찾기
for f in fm.fontManager.ttflist:
if 'Gothic' in f.name:
print(f.fname)
# 여러 폰트 경로 중 원하는 폰트 경로 설정하기
font_path = 'C:\Windows\Fonts\malgun.ttf'
4) 원하는 모양대로 wordcloud 그리기
# 이미지 불러오기
mask = np.array(Image.open('./data/sparta.png'))
# wordcloud 그리기
wc = WordCloud(font_path=font_path, background_color="white", mask=mask)
wc.generate(text)
f = plt.figure(figsize=(50,50))
plt.imshow(wc, interpolation='bilinear')
plt.title('Sparta Cloud', size=40)
plt.axis("off")
plt.show()
# 이미지 저장하기
f.savefig('./data/wordcloud.png')
3. 시간, 날짜 데이터 전처리하기
%Y 연도 %m 월 %d 일 %H 시 %M 분 %S 초 %f 소숫점 T 띄어쓰기
# 문자열로 된 시간 정보 데이터를 실제 시간 데이터로 바꿔주기
format='%Y-%m-%dT%H:%M:%S.%f'
# 컬럼에 추가하기
data['date_time'] = pd.to_datetime(data['date_time'], format=format)
월화수목금토일 순서대로 데이터 정렬하기
weeks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
data = data.agg(weeks)
시간/날짜 데이터 추출하기
data['date_time_hour'] = data['date_time'].dt.hour
data['date_time_weekday'] = data['date_time'].dt.day_name()
※ date_time에 {2021-12-01 18:21:05.247} 형식의 데이터가 담겨있다고 하면,
.dt.hour를 통해 {18}이 .dt.day_name()을 통해 {Wednesday}가 추출되서 각각 "date_time_hour", "date_time_weekday"라는 column에 담기게 된다.
4. pivot table 만들기
행에 요일, 열에 시간을 넣어서 요일마다 시간별로 수강생 수를 구하고자 한다.
weeks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
pivot_table = pd.pivot_table(data, values='student_count',
index = ['date_time_weekday'],
columns = ['date_time_hour'],
aggfunc="count").agg(weeks)
※ data 분석할 데이터, index 행, columns 열, aggfunc 분석방법을 뜻한다.
위에서는 'student_count'를 요일마다 시간별로 count하는 분석 방법을 사용했고, weeks로 index 순서를 정렬시켰다.
5. 히트맵 그리기
X축과 Y축을 변수로 해서 균일한 블록으로 나누어 각 칸의 수치나 빈도를 색을 통해 시각적으로 나타내는 격자형 차트이다.
plt.figure(figsize=(14,5))
plt.pcolor(pivot_table)
# X축, Y축 항목 설정
plt.xticks(np.arange(0.5, len(pivot_table.columns), 1), pivot_table.columns)
plt.yticks(np.arange(0.5, len(pivot_table.index), 1), pivot_table.index)
plt.title('요일별 종료 시간 히트맵')
plt.xlabel('시간')
plt.ylabel('요일')
plt.colorbar()
plt.show()
※ np.ragane(눈금 위치, 눈금 갯수, 눈금 간격)
개발 업무 내용📑
최애곡 가사 wordcloud 만들기
이슈😲
최애곡 가사 wordcloud를 만드는 것은 사실 저기 비어져 있는 형태로 데이터를 넣고 싶었던 거라 내가 목표했던 것에는 달성하지 못한 채 숙제를 낸 상태라 나중에 구글링을 통해서 다시 한 번해봐야 될 것 같다.
마무리 소감😉
예전에 애정하는 프로그램인 무한도전에 빅데이터 전문가가 나와서 무한도전 관련 키워드로 wordcloud를 만들어서 보여준 적이 있었다. 물론, 그 때는 그걸 wordcloud라고 부르는건지도 몰랐지만 방송한 지 10년이 넘었는데도 여전히 뇌리 속에 선명히 박혀있었어서 wordcloud가 나왔을 때 내적 친밀감을 느꼈다.
당시에는 아주 어렵고 복잡한 과정을 거치는 줄 알았는데, 막상 해보니 생각보다 간단해서 놀라기도했다. 물론, 10년 전에는 이렇게 데이터 분석이 상용화되지 않았을 때니 훨씬 복잡하고 어려운 과정을 거쳤겠지만 어쨌든 나도 만들 수 있다는 것에 만족감을 느낀다.