커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
5주차 숙제 코드
undefined주차
북마크
유*연
댓글
8
추천
0
조회수
16
조회수
16
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


5주차 숙제 코드 중에 모르겠는 부분 질문드립니다.

1.날짜 데이터 코드 입력

앞선 강의에서 진행할 때는

sparta_data['start_time'] = pd.to_datetime(sparta_data['created_at'], format='mixed')

으로 진행했는데 숙제 완성 코드에는

sparta_data['start_time'] = pd.to_datetime(sparta_data['created_at'], format=format,infer_datetime_format=True)

으로 제시 되어있는데 제시된 코드로 진행하면 오류가 떠요. 강의 중에 했던 코드로 진행하면 문제가 없는데 제시된 코드가 틀린 건가요?


2.주차별 수강 전환율 구하기

숙제해설 영상에서는

for j in range(5, 0, -1):

으로 설명해주시고, 이렇게 해야 결과가 나오는데

제공된 답안지에는

for j in range(0, 6, 1):

라고 제시되어 있습니다. 여기도 답안지가 틀린 걸까요?


어디가 틀렸을지 몰라 제가 작성한 코드 전체 첨부합니다!(일단 위에 언급한 부분들을 답안지와 다르게 작성하면 숙제 해설 영상과 같은 결과가 나오기는 합니다)





작성한 코드 및 에러 메세지

#라이브러리 불러오기
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
plt.rc('font', family='NanumBarunGothic')


# 한글깨짐 방지
plt.rc('font', family='NanumBarunGothic')
sparta_data = pd.read_table('/content/cohort_data.csv',sep=',')
sparta_data.tail()


#날짜 데이터 타입 변경
format='%Y-%m-%dT%H:%M:%S.%f'
sparta_data['start_time'] = pd.to_datetime(sparta_data['created_at'], format='mixed')
sparta_data.tail()


#시작 week 구하기
sparta_data['start_week']= sparta_data['start_time'].dt.isocalendar().week
sparta_data.tail()


#시작 주 범위 알기
category_range = set(sparta_data['start_week'])
category_range


# 범주화 하기
#번주화할 데이터 
progress_rate = list(sparta_data['progress_rate'])
progress_rate


#범주를 구분하는 기준 bins
bins = [0,4.11,26.03,41.10,61.64,80.82,100]


#구분한 범주의 라벨 labels
labes=[0,1,2,3,4,5]


#범주화에 사용하는 함수 pd.cut
cuts = pd.cut(progress_rate,bins, right=True,include_lowest=True, labels=labes)
cuts
cuts = pd.DataFrame(cuts)
cuts.tail()


# 표 합치기
sparta_data = pd.concat([sparta_data,cuts],axis=1, join='inner')
sparta_data.head()


#표 인덱스 변경하기
sparta_data.columns=['created_at','user_id','name','progress_rate','start_time','start_week',"week"]
sparta_data.head()


#시작주와, 수강 주차별 기준으로 표 grouping 하기
grouping = sparta_data.groupby(['start_week', 'week'], observed=False)


grouping.head()


#시작주와, 수강 주차별에 해당하는 수강생 수 구하기
cohort_data = grouping['user_id'].apply(pd.Series.nunique)
cohort_data = pd.DataFrame(cohort_data)
cohort_data.head(10)


#각 주차별 수강한 수강생 총 합 구하기
k=31
for i in range(6):
  for j in range(5, 0, -1):
    cohort_data.at[(k,j-1), 'user_id'] = int(cohort_data.at[(k,j),'user_id']) +  int(cohort_data.at[(k,j-1),'user_id'])
  k=k+1
cohort_data = cohort_data.reset_index()
cohort_data.head()
cohort_counts = cohort_data.pivot(index="start_week",
                                  columns="week",
                                  values="user_id")
cohort_counts


# 앞서 만든 피벗 테이블을 retention 변수에 저장하기
retention = cohort_counts
#각 주(week) 별 최초 수강생 수만 가져오기
cohort_sizes = cohort_counts.iloc[:,0]
cohort_sizes.head()


# 최초 수강생 수를 각 데이터에 나눠주기
retention = cohort_counts.divide(cohort_sizes, axis=0)
retention


#각 수치 퍼센트로 변경하기
retention.round(3)*100


#주차별 수강 전환율 구하기
w=31
for i in range(6):
  for j in range(5, 0, -1):
    retention.at[(w,j)] = retention.at[(w,j)]/retention.at[(w,j-1)]
  w=w+1


  retention


  #주차별 수강 전환율 히트맵 
plt.figure(figsize=(10,8))


sns.heatmap(data=retention,
           annot=True,
           fmt='.0%',
           vmin=0,
           vmax=1,
           cmap="BuGn")




plt.title('개강일별 주차 간 전환율', fontsize=20)
plt.xlabel('주차', fontsize=14,labelpad=30)
plt.ylabel('개강일', fontsize=14,rotation=360,labelpad=30)
plt.yticks(rotation=360)


plt.show()




1번 관련 오류코트

ValueError                                Traceback (most recent call last)
<ipython-input-15-13ad6a949d38> in <cell line: 14>()
     12 #날짜 데이터 타입 변경
     13 format='%Y-%m-%dT%H:%M:%S.%f'
---> 14 sparta_data['start_time'] = pd.to_datetime(sparta_data['created_at'], format=format,infer_datetime_format=True)
     15 sparta_data.tail()
     16 





2번 관련 오류코드

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key)
   3790         try:
-> 3791             return self._engine.get_loc(casted_key)
   3792         except KeyError as err:

index.pyx in pandas._libs.index.IndexEngine.get_loc()

index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: -1
The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)



취소
 공유
취소
댓글 0
댓글 알림
나의얼굴