- 행과 열로 구성된 사각형 모양의 표.
- 열은 속성. column or varaible.
- 행은 각 개체의 정보. row or case.
- 엑셀 : read_excel()
header= None 하면 첫번째 행을 변수명이 아닌 데이터롤 인식
sheet_name=' ' 특정 시트의 데이터만 불러올 수 있다- CSV: read_csv()
csv 만들기 : to_csv()
index=False 하면 인덱스 번호 제외 후 저장.
데이터 파악하기
- .head() : 앞에서 다섯 행까지, 숫자 입력하면 그 행 까지.
- .tail() : 뒤 부터
- .shape : 데이터 프레임 크기, 함수 아닌 attribute.
- .info() : 변수 속성
- .describe() : 요약 통계량
count
mean
std
min
max
unique : 중복의 제거한 범주의 개수
top : 개수가 가장 많은 값
freq : 개수가 가장 많은 값의 개수
- 기존 값 이용해 새로운 값 만들어 column 추가 가능
mpg_new['total'] =(mpg_new['city'] + mpg_new['highway'])/2 mpg_new['total'].mean() #평균과 비교 가능.
- 조건문 이용하기
np.where()
rot=0 : 축 이름 수평으로.mpg_new['test'] = np.where(mpg_new['total']>=20, 'pass','fail') mpg_new['test'].value_counts() # pass 128 fail 106 Name: test, dtype: int64 # count_test = mpg_new['test'].value_counts() count_test.plot.bar(rot=0)
- 중첩 가능
sort_index() : 알파벳순으로 막대 정렬mpg_new['grade'] = np.where(mpg_new['total']>=30, 'A', np.where(mpg_new['total']>=20,'B','C')) # count_grade = mpg_new['grade'].value_counts().sort_index()
- 목록에 해당하는 행으로 변수
.isin() 쓰면 간단mpg_new['size'] = np.where((mpg_new['category'] == 'compact') | (mpg_new['category']=='subcompact')| (mpg_new['category'] == '2seater'),'small','large') # mpg_new['size'] = np.where(mpg['category'].isin(['compact','subcompact','2seater']),'small','large')
- .query(' ') : 조건에 맞는 행 추출
- df[ ]
여러 변수 함꼐 추출 시 *df[ [ ] ]
조합 가능exam.query('nclass in [1,3,5]')['english']
- sort_values()
내림 차순 : ascending = False
여러 개 지정 하려면 [ ] 이용해 변수명 나열exam.sort_values(['nclass', 'math'], ascending=[True,False])
- .assign() 에 새 변수명 = 변수를 만드는 공식입력
exam.assign( total = exam['math'] + exam['english'] + exam['science'], mean = (exam['math'] + exam['english'] + exam['science'])/3 ) # where 적용 exam.assign(test = np.where(exam['science']>=60, 'pass', 'fall')) #lambda 이용 exam.assign(total = lambda x : x['math'] + x['english'] + x['science'], mean = lambda x : x['total']/3)
- .agg() : 요약값을 할당할 변수명과 =를 입력 후 값을 요약하는데 사용할 변수와 함수를 괄호 안에 나열
exam.agg(mean_math = ('math', 'mean'))
- .groupby() : 변수의 범주별로 데이터를 분리
exam.groupby('nclass').agg(mean_math = ('math','mean'))
as_index =False : 변수를 인덱스로 바꾸지 않고 유지
exam.groupby('nclass').agg(mean_math = ('math','mean'), sum_math = ('math','sum'), median_math = ('math','median'), n= ('nclass','count'))
- 집단별로 다시 집단 나누기
mpg.groupby(['manufacturer', 'drv']) .agg(mean_cty = ('cty', 'mean')) # mean_cty manufacturer drv audi 4 16.818182 f 18.857143 chevrolet 4 12.500000 f 18.800000 r 14.100000 (..생략..) # mpg.query('manufacturer == "audi" ') .groupby(['drv']) .agg(n=('drv','count'))
- value_counts() 이용하면 집단별 빈도 더 간단히 구할 수 있지만 출력 결과가 series 여서 query() 적용 불가
mpg['drv'].value_counts() # f 106 4 103 r 25 Name: drv, dtype: int64
- 가로로 합치기 : pd.merge()
how ='left' : 오른쪽에 입력한 데이터 왼쪽에 결합
on = ' ' : 기준으로 삼을 변수명 입력test1 = pd.DataFrame({'id': [1,2,3,4,5], 'midterm':[60,80,70,90,85]}) test2 = pd.DataFrame({'id' :[1,2,3,4,5], 'final': [70,83,65,95,80]}) total= pd.merge(test1,test2, how = 'left', on='id') total # id midterm final 0 1 60 70 1 2 80 83 2 3 70 65 3 4 90 95 4 5 85 80
- 세로로 합치기 : pd.concat([ ])
ignore_index = True : 인덱스 새로 부여group_all = pd.concat([group_a,group_b],ignore_index=True)
추가 주의 사항
- assign() 사용 시 반드시 기존 df에 대입 해야한다
- np.where() 여러 번 사용 할 때
midwest=midwest.assign(perchildrank = np.where(midwest['perchild']>=40,'large' ,np.where(midwest['perchild']>=30,'middle','small')))