빅데이터 분석기사 66

Q67 ~ 79 dt 시계열 전처리 잔뜩

q67Yr_Mo_Dy에 년도가 2061년 이상의 경우에는 모두 잘못된 데이터이다. 해당경우의 값은 100을 빼서 새롭게 날짜를 Yr_Mo_Dy 컬럼에 정의하라def fix_century(x): import datetime year = x.year - 100 if x.year >= 2061 else x.year return pd.to_datetime(datetime.date(hyear, x.month, x.day))df['Yr_Mo_Dy'] = df['Yr_Mo_Dy'].apply(fix_century)q68df.groupby('Yr_Mo_Dy'.dt.year).mean()q69 dt.weekday df['weekday'] = df['Yr_Mo_Dy'].dt.weekdayq70조건 하나 ..

pandas 1 axis=0, 1, describe(inclue='O'), astype() 유의

시리즈 만들기데이터프레임 만들기menu = pd.Series(['아아','아라','바콜'])menu # 데이터 프레임 만들기 pd.DataFrame({"컬럼명":데이터})pd.DataFrame({    'menu' : menu,    'price' : price}) object형 칼럼 기초통계Object의 Odescribe(include='O')# 기초 통계 (object)# O 는 알파벳 대문자 df.describe(include='O')  메뉴count 7unique 7top 아메리카노freq 1 결측값은 Numpy 패키지 사용# 결측값으로 추가, 원두 컬럼을 만들고 결측값(NaN)으로 대입# 결측값을 넣을 때는 np 사용함import numpy as npdf['원두'] = np.nandf 데이터 삭..

Q ~ 66 groupby, lambda, map

value_counts()각 칼럼의 갯수 구함normalize=True 빈도 구하는 파라미터 # q45 데이터의 각 host_name의 빈도수를 구하고, host_name 정렬해 상위 5개 출력하라# df.value_counts('host_name', normalize=True).head()df.host_name.value_counts().sort_index().head()host_name'Cil 1(Ari) HENRY LEE 1(Email hidden by Airbnb) 6(Mary) Haiy 1-TheQueensCornerLot 1Name: count, dtype: int64size() 메소..

python 2, 3 - 인덱싱, 슬라이싱, 반복분 -enumerate(), def 함수

오류 모음1. AttributeError# 밸류 값# dictbox.values()# di에는 이런 속성이 없다는 의미 -> 오류 di.value()AttributeError: 'dict' object has no attribute 'value'2. IndexErrorlistbox = [2,4,6,8,10]# list[index] 원소 값# print(listbox[0]) # index 첫번째 값# print(listbox[3]) # index 3 (네번째)# python은 index는 0부터 시작함# 첫번째 인덱스 값을 출력하려면 0을 써야 함# 범위가 넘어섰다는 에러 메세지를 받게 됨 -> 오류listbox[5]IndexError: list index out of range3. NameError#..

데이터 전처리 100문제 Q20~43 - duplicate(), str, isin()

filteringdf.loc[df['quantity']==3].head()reset_index(drop=True)# q22 reset_index() 안에 drop True 안 쓰면 index 칼럼이 새로 생김 꼭 추가하기ans = df.loc[df['quantity']==3].reset_index(drop=True).head()print(ans)and -> & !!!df['new_price'] = df.new_price # q27 조건 and -> & 틀림# ()로 묶기# 복잡할 때는 df.new_price 가능# df.loc[(df['new_price'] sort_values('new_price', ascending=False)파라미터 ascending# sort_values 내림차순 파라미터는 asc..

python 1 - 주석 cltr + /, 내어쓰기 shift + tab

# 셀의 마지막 행에 입력했을 때는 print를 안 해도 출력이 됨# 하지막 두 줄 입력시에는 마지막 거가 나옴213456456  한 줄만 주석 처리(해제) : Ctrl + / (맥 Command + /)여러 줄 주석 처리(해제) : 블록지정 후 Ctrl + / (맥 Command + /)# 주석입니다.# 파이썬은 들여쓰기가 예민하고# 에러가 뜨면 들여쓰기가 잘못된 것임!# 주석쓰기 할 때 shift+ 3 을 누르는 사람 없음# ctrl + /를 입력해야 함 - 유용한 단축기임!!!!! print("파이썬 공부 중") # 출력문print("파이썬은 쉽다") File "", line 2 print("파이썬 공부 중") # 출력문 ^IndentationError: unexpected inde..

데이터 전처리 100문제 Q1~19 - selecte_dtypes(), quantile()

# 11q - 틀림# select_dtypes()# selected_dtypes 아님!!# 메소드 안에서 exclude, include로 조건 설정 가능 ans = df.select_dtypes(exclude=object).columnsans# Q17평균 속도 컬럼의 4분위 범위 값을 구하라# quantile 함수 활용하기# 잘못된... 답 ㅋㅋㅋ# q3 = df['평균 속도']* 0.75%# q1 = df['평균 속도']* 0.25%# IQR = q3 - q1# print(IQR)df['평균 속도'].quantile(0.75) - df['평균 속도'].quantile(0.25)

변수대로, 디폴트는 내림차순, datetime 변경, merge, np.where()

새로 변수 만들었음(head) -> head 에 그대로 조건을 넣고 추출해야 함 # 나이 순(내림차순)으로 정렬 df = df.sort_values('age', ascending=False).reset_index(drop=True) #print(df) # head로 만들었으니까 계속 쭉 이거로 조건에 대한 수치를 추출해야함 # 그렇지 않으면 head = df.head(20) head['f1'] = head['f1'].fillna(head['f1'].median()) cond = (head['f4']=='ISFJ') & (head['f5'] >= 20) print(head[cond]['f1'].mean()) 내림차순 디폴트값 -> 내림인지 오름이지 잘 확인하기 내림차순 -> ascending = True ..

대립가설 기준, loc 인덱싱

후에서 전을 빼는 것을 잘 기억하기 대응, 쌍체 -> 두 개라는 의미기 때문에 두 개가 관계가 있다!는 것은 rel ttest_1samp, ttest_ind import scipy.stats from ttest_rel # 후 - 전 # a(after) - b(before) mean = (df['bp_post'] - df['bp_pre']).mean() print(round(mean,2)) st, pv = ttest_rel(df['bp_post'], df['bp_pre'], alternative = 'less') print(round(st,4)) print(round(pv,4)) print('기각'if pv alternative = 'greater' 75로 수치가 정해짐 -> ttest_1samp 사실 어..

상위 5퍼 = quantile(0.95), 시간에 따라 증가시 마지막(max) 선택, 상관계수는 절댓값 사용, 멀티인덱싱

Minmax quantile 헷갈릴 수도 있으나!! 가로막대그래프를 그렸을 때 오른쪽으로 갈수록 숫자가 커짐 -> 상위 5퍼는 0.95를 의미함 정규화 from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaled = scaler.fit_transform(df[['f5']]) top, down = scaled.quantile([0.95,0.5]) print(int(top, down)) 시간이 지남에 따라 점점 접종률이 증가함 groupby 썼으면 해당하는 통계함수 뭐 쓸건지 고민해야 함! 시간이 지남(오래됨, 숫자 증가함) -> 가장 마지막이 country의 백신률을 알 수 있음 df2 = df.groupby(country).m..