데이터 분석 4주차 복습 완강&숙제
1) 차트 한글 변환 필수 코드(코드 따로)
! sudo apt-get install -y fonts-nanum
! sudo fc-cache -fv
! rm ~/ . cache/matplotlib -rf
1-1) 본 코드에 입력
plt.rc ( 'font' , family= 'NanumBarunGothic' )
2) 공란 셀 삭제, 그룹바이 코드
sparta_data=sparta_data.dropna ()
access_media=sparta_data.groupby ( 'access_media' )[ 'user_id' ] .count ()
3) 그래프 바 색상 변경 방법
- x축,y축 기재 후 ,color='원하는 색상' 을 추가로 기재한다
plt.bar ( access_media.index , access_media , color= 'green' )
4) 각 바의 수치 나타내기
*주의점 : bar = plt.h bar(access_media.index,access_media.values)는 안된다
-> hbar로 기재시 바 그래프가 가로로 나타나는데 이럴 땐 오류남
#그래프를 bar라는 변수에 넣고, bar = plt.bar(access_media.index,access_media.values) #for 반복문으로, for rect in bar: #각 바의 세로길이 값을 구하고, height = rect.get_height() #bar의 가장 정 가운데 x 좌표 구하기 : get_x()로 x축의 가장 왼쪽 부분 + get_width의 절반 값 plt.text(rect.get_x() + rect.get_width()/2.0, height, '%.1f' % height, ha='center', va='bottom', size = 12)
### 해석: 바 그래프 마다 높이를 정해서 텍스트를 추가하는데 해당 직사각형 x 좌표, x좌표 너비의 1/2 높이 맞는곳에다가 height 값을 적어줘
5) 바 그래프에서 바 별 색상 변경&테두리 색상 변경&바,테두기 두께 변경
color = [ 'gold' , 'b' , '#FF0000' , 'green' , 'orange' , 'red' , '#000000' ]
첫번째 금 / 두번째 파랑 / 세번째 #ff0000 / 네번째 초록 .....
edgecolor : 테두리 색상
linewidth : 테두리 두께
width : 바 두께
bar = plt.bar ( access_media.index , access_media.values , color = [ 'gold' , 'b' , '#FF0000' , 'green' , 'orange' , 'red' , '#000000' ], alpha = 0.3 , edgecolor = 'black' , linewidth = 2 , width= 0.5 )
6) 가능 편한거 써
이거랑
bar = plt.bar ( access_media.index , access_media.values , color = [ 'gold' , 'b' , '#FF0000' , 'green' , 'orange' , 'red' , '#000000' ], alpha = 0.3 , edgecolor = 'black' , linewidth = 2 , width=0.5 )
요거
plt.bar ( access_media.index , access_media , color= 'green' )
둘 다 그래프 출력에 문제 없음
plt.bar ( access_media.index , access_media.values , color = [ 'gold' , 'b' , '#FF0000' , 'green' , 'orange' , 'red' , '#000000' ], alpha = 0.3 , edgecolor = 'black' , linewidth = 2 , width= 0.5 )
이렇게도 가능
plt.bar ( access_media.index , access_media.values , color= 'green' )
이것도 가능 시발?
7) 필요 자료 추출 (groupby 랑 비슷함)
###선택하면 1 인데 값이 1인 것만 카운트해서 알아보자
sum_of_students_by_class=sparta_data [ sparta_data== 1 ] .count ()
8) 불필요한 데이터 삭제
user_id 데이터는 데이터 분석 목적 대비 쓸모없는 자료임
##필요없는 데이터 삭제(user_id)
sum_of_students_by_class=sum_of_students_by_class.drop ( 'user_id' )
sum_of_students_by_class
9) groupby 복습
###
app_users_goal=sparta_data_app.groupby ( 'goal' )[ 'user_id' ] .count ()
game_users_goal=sparta_data_game.groupby ( 'goal' )[ 'user_id' ] .count ()
앱 유저의 목표 = 스파르타 데이터 앱에서 목적별로 유저 총 몇 명인지 알려줘
게임 유저의 목표 = 스파르타 데이터 게임에서 목적별로 유저 총 몇 명인지 알려줘
10) 그래프 살찌우기 범례
####각 그래프의 범례는 .legend()을 이용하여 만들어 줍니다! :)
plt.legend ()
10) 4주차 숙제 강의 자료와 내가 작업한 자료 비교 대조
결론 : 더 간단한 방법이 있는데 써먹을줄 모른다 -> 감이 덜 잡혔다 -> 감이 없다 -> 아까비
#4주차 숙제
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.rc ( 'font' , family= 'NanumBarunGothic' )
# 목적 : 결제 할인율이 결제 전환율에 유의미한지 알아보자
# 가설 : 할인율이 높을수록 결제 전환율이 높을 것 이다.
sparta_data=pd.read_table ( '/content/user_db1.csv' , sep= ',' )
sparta_data.head ()
## user_id / gender / area / age / access_media / group / discounted 인데 내가 필요한 자료는 할인 적용 그룹의 결제 전환율이 높은걸 알았으니
## 할인 금액별 결제 전환율은 어떻게 되는지 알아보자.
sum_of_students_by_discounted=sparta_data [ sparta_data [ 'group' ] == 1 ][ 'user_id' ] .count ()
sum_of_students_by_discounted
## 5654명 할인 받음
sum_of_students_by_discounted_10000=sparta_data [ sparta_data [ 'discounted' ] == 10000 ][ 'user_id' ] .count ()
sum_of_students_by_discounted_10000
## 만원 808명 결제 전환
sum_of_students_by_discounted_20000=sparta_data [ sparta_data [ 'discounted' ] == 20000 ][ 'user_id' ] .count ()
sum_of_students_by_discounted_20000
### 이만원 1588명 결제 전환
sum_of_students_by_discounted_30000=sparta_data [ sparta_data [ 'discounted' ] == 30000 ][ 'user_id' ] .count ()
sum_of_students_by_discounted_30000
### 삼만원 3258명 결제 전환
########상기 내용을 축약해서 나타낼 수 있음
######### 수강 신청한 수강자 중에 할인 적용 범위를 %가 아닌 총 명 수로 나타내면 훨씬 편했음
# 참고 ::
#각 할인별 신청한 수강생 수 구하기
#students_discounted = sparta_data.groupby('discounted')['user_id'].count()
#students_discounted
percent_of_students_by_discounted_10000=sum_of_students_by_discounted_10000/ 5654 * 100
percent_of_students_by_discounted_20000=sum_of_students_by_discounted_20000/ 5654 * 100
percent_of_students_by_discounted_30000=sum_of_students_by_discounted_30000/ 5654 * 100
print ( percent_of_students_by_discounted_10000 , percent_of_students_by_discounted_20000 , percent_of_students_by_discounted_30000 )
#그래프 사이즈
plt.figure ( figsize= ( 10 , 5 ))
#x 그룹 지정하기
x_list = [ '만원 할인' , "이마넌 할인" , '슴매넌 할인' ]
#y 값
#각각 어떤 값이 들어가야 하는지 입력해 볼까요?
y_list = [ percent_of_students_by_discounted_10000 , percent_of_students_by_discounted_20000 , percent_of_students_by_discounted_30000 ]
#x,y값 설정
plt.bar ( x_list , y_list )
#그래프 타이틀
plt.title ( '할인 금액별 수강자(%) 비교 분석' , fontsize= 18 )
#x축 레이블
plt.xlabel ( '할인 금액' , fontsize= 14 )
#y축 레이블
plt.ylabel ( '할인 받은 수강자(%)' , fontsize= 12 )
#그래프 보여주기
plt.show ()
#결과 : 할인 받은 수강자 중에 삼만원 할인 받아서 수강 결정한 수강자가 57.6% / 이만원 28.1% / 일만원 14.3% 로 나타남
#결론 : 할인율이 높을수록 수강할 확률이 높다
#그래프 사이즈
#plt.figure(figsize=(10,5))
#x_list =["1만원 쿠폰 그룹", "2만원 쿠폰 그룹", "3만원 쿠폰 그룹"]
#x,y값 설정
#plt.bar(x_list, students_discounted.values)
#그래프 타이틀
#plt.title('할인 율 별 수강 신청 자 수')
#x축 레이블
#plt.xlabel('할인 적용 범위')
#y축 레이블
#plt.ylabel('수업 신청한 수강생')
#그래프 보여주기
#plt.show()
11) 팀별 과제는 언제나 머리 아프다
원활한 의사소통을 위해서?
1. 소통 수단이 건강해야한다
- 마이크,웹캠, 건강한 컴퓨터
2. 짧고 간결하게 말해보자 사설이 너무 길어
3. 다들 잘해주고 있다 나만 조심하자
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
데이터 분석 5주차-1~5
1) 매번 복기해도 모잘라
! sudo apt-get install -y fonts-nanum
! sudo fc-cache -fv
! rm ~/ . cache/matplotlib -rf
plt.rc ( 'font' , family= 'NanumBarunGothic' )
2) groupby 복습
process_rate_by_age=sparta_data.groupby ( 'age' )[ 'progress_rate' ] . sum ()
process_rate_by_age
number_people_by_age=sparta_data.groupby ( 'age' )[ '_id' ] .count ()
number_people_by_age
average=process_rate_by_age/number_people_by_age
average
3) for 문 사용 시 주의 사항
bar=plt.bar ( average.index , average , width= 8 )
for rect in bar :
height = rect.get_height ()
plt.text ( rect.get_x () + rect.get_width () / 2.0 , height , '%.1f' % height , ha= 'center' , va= 'bottom' , size = 12 )
plt.bar ( average.index , average , width= 8 )
for 문 안쓰면 윗 문장으로도 그래프 출력됨 단, for 문 사용 시 bar에 대한 자료가 필요해서 아랫 문장처럼 쓰임
bar=plt.bar ( average.index , average , width= 8 )
4) 폰트 사이즈, 폰트 여백, 회전 복습
plt.title ( '[나이대별 평균 수강율]' , fontsize= 15 , pad= 20 )
plt.xlabel ( '나이' , fontsize= 12 , labelpad= 20 )
plt.ylabel ( '평균 수강율' , fontsize= 12 , labelpad= 40 , rotation= 360 )
5) 코드 독해력, 코드 이해도 증가를 위해
*이건 통째로 봐라 미래의 나 자신아
import matplotlib.pyplot as plt
plt.rc ( 'font' , family= 'NanumBarunGothic' )
import pandas as pd
sparta_data=pd.read_table ( '/content/sprata_data.csv' , sep= ',' )
sparta_data.head ()
####_id / created_at / updated_at / name / marketing / managed / gender / age / progress_rate
sparta_data.info ()
######managed 는 boolean 타입이다 = true/false 타입이다 -> 문자형으로 바꿔줘야 인식한다 =>
managed= [ 'TRUE' , 'FALSE' ]
managed
managed_true_data=sparta_data.groupby ( 'managed' )[ 'progress_rate' ] . sum () /sparta_data.groupby ( 'managed' )[ '_id' ] .count ()
managed_true_data
###틀림 왜?
#plt.figure(figsize=(10,6))
#나이가 여기서 왜 나와ㅡㅡ 삭제 필요
#plt.xticks([10,20,30,40,50])
#안했었음 plt.bar(managed_true_data.index,managed_true_data,width=0.8)
#bar=plt.bar(managed_true_data.index,managed_true_data,width=0.8)
#for rect in bar:
# height = rect.get_height()
# plt.text(rect.get_x() + rect.get_width()/2.0, height, '%.1f' % height, ha='center', va='bottom', size = 12)
#plt.title('[찐한 관리 평균 완주율]',fontsize=15,pad=20)
#plt.xlabel('나이',fontsize=12,labelpad=20)
#plt.ylabel('평균 완주율',fontsize=12,labelpad=40,rotation=360)
##정답
plt.figure ( figsize= ( 6 , 6 ))
plt.bar ( managed_true_data.index , managed_true_data )
bar = plt.bar ( managed_true_data.index , managed_true_data )
for rect in bar :
height = rect.get_height ()
plt.text ( rect.get_x () + rect.get_width () / 2.0 , height , '%.1f' % height , ha= 'center' , va= 'bottom' , size = 12 )
plt.title ( '찐한관리 유무에 따른 평균 완주율' , fontsize= 14 )
plt.xlabel ( '평균 완주율' , fontsize= 12 )
#기존의 0,1이라는 x축 레이블을, labels =["..."]로 변경 가능 합니다 :)
plt.xticks ([ 0 , 1 ], labels= [ "찐한관리 비 신청자" , "찐한관리 신청자" ])
plt.ylabel ( '찐한관리 여부' , fontsize= 12 , rotation= 360 , labelpad= 35 )
plt.xticks ( rotation= 45 )
plt.yticks ( rotation= 360 )
#없어도 그래프 출력되는데 왜 필요한걸까?
plt.show ()