
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
5주차 7강 마지막 마무리 부분에서
코드스니펫 수강 주차 별 수강한 총 인원 구하기 코드 입력 후
코드스니펫 인덱스 새롭게 설정하기 코드 입력하니까
결과에 오류가 생기네요 이유가 뭔가요?

작성한 코드 및 에러 메세지
cohort_data = cohort_data.reset_index()
#라이브러리 불러오기
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
plt.rc('font', family='NanumBarunGothic')
sparta_data = pd.read_table('/content/cohort_data.csv',sep=',')
sparta_data.head()
#파이썬의 type()함수를 쓰면, 데이터의 종류를 확인 할수 있어요 :)
print(type(sparta_data['created_at'][1]))
#sparta_date 정보에서 access_date 열에서 데이터 첫번째 부분만 확인 하면 되겠죠?
format='%Y-%m-%dT%H:%M:%S.%f'
sparta_data['start_time'] = pd.to_datetime(sparta_data['created_at'], format='mixed',infer_datetime_format=True)
sparta_data.info()
#수강 시작 주 구하기
sparta_data['start_week']= sparta_data['start_time'].dt.isocalendar().week
sparta_data.tail()
#수강 시작 주 구하기
sparta_data['start_week']= sparta_data['start_time'].dt.isocalendar().week
sparta_data.tail()
#이전에 배웠듯이 set()은 set안의 데이터는 순서가 정해져있지 않고, 중복되지 않는 고유한 요소를 가져옵니다!
category_range = set(sparta_data['start_week'])
category_range
progress_rate = list(sparta_data['progress_rate'])
progress_rate
#범주를 구분하는 기준 bins 처음(0)과 끝(100) 잊지 말고 기입 해주세요!
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.head()
#concat() 함수를 이용하여, sparta_data 테이블과, cuts 테이블 병합 할수 있습니다 :)
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()
#기존의 테이블을, start_week와, week로 묶어줍니다!
grouping = sparta_data.groupby(['start_week','week'])
grouping.head()
cohort_data = grouping['user_id'].apply(pd.Series.nunique)
cohort_data = pd.DataFrame(cohort_data)
cohort_data.head(5)
#첫 주가 31주니 변수를 하나 만들어 줍니다!
f=31
#처음 수강 시작한 주의 범위가 {31,32,33,34,35,36} 이니, range(6)으로 합시다!
for i in range(6):
#5주차의 강의가 마지막이고, 0주차까지 이니, 시작은 5에서 시작해 1씩 0까지 감소 시킬수 있어요!
for j in range(5, 0, -1):
cohort_data.at[(f,j-1), 'user_id'] = int(cohort_data.at[(f,j),'user_id']) + int(cohort_data.at[(f,j-1),'user_id'])
#주차는(31부터 32 33..) 1씩 늘어나죠?
f=f+1
cohort_data = cohort_data.reset_index()
cohort_data.head()
<class 'str'>
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1736 entries, 0 to 1735
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 created_at 1736 non-null object
1 user_id 1736 non-null object
2 name 1736 non-null object
3 progress_rate 1736 non-null int64
4 start_time 1736 non-null datetime64[ns]
dtypes: datetime64[ns](1), int64(1), object(3)
memory usage: 67.9+ KB
<ipython-input-46-b074710b6572>:15: UserWarning: The argument 'infer_datetime_format' is deprecated and will be removed in a future version. A strict version of it is now the default, see https://pandas.pydata.org/pdeps/0004-consistent-to-datetime-parsing.html. You can safely remove this argument.
sparta_data['start_time'] = pd.to_datetime(sparta_data['created_at'], format='mixed',infer_datetime_format=True)
<ipython-input-46-b074710b6572>:55: FutureWarning: The default of observed=False is deprecated and will be changed to True in a future version of pandas. Pass observed=False to retain current behavior or observed=True to adopt the future default and silence this warning.
grouping = sparta_data.groupby(['start_week','week'])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-46-b074710b6572> in <cell line: 65>()
66 #5주차의 강의가 마지막이고, 0주차까지 이니, 시작은 5에서 시작해 1씩 0까지 감소 시킬수 있어요!
67 for j in range(5, 0, -1):
---> 68 cohort_data.at[(f,j-1), 'user_id'] = int(cohort_data.at[(f,j),'user_id']) + int(cohort_data.at[(f,j-1),'user_id'])
69 #주차는(31부터 32 33..) 1씩 늘어나죠?
70 f=f+1
3 frames
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/range.py in get_loc(self, key)
415 raise KeyError(key) from err
416 if isinstance(key, Hashable):
--> 417 raise KeyError(key)
418 self._check_indexing_error(key)
419 raise KeyError(key)
KeyError: (32, 5)
오류 발생 시, 작성한 코드 전체와 에러 메시지를 첨부해 주세요.
Tip 1) </> 아이콘을 눌러 코드박스를 만들어 보세요.
Tip 2) Ctrl+A(맥의 경우 Command+A) 단축키로 코드를 한 번에 선택할 수 있어요!
