강의자료/머신러닝

[딥러닝파이썬] 02-4.파이썬의 Pandas를 다뤄 보자.

파아란 기쁨 2022. 5. 24. 20:07
Group by

- SQL 의 Group by 명령어와 같이 그룹별로 집계하는 기능

from pandas import DataFrame,Series
import pandas as pd
import numpy as np

pd_data = pd.read_csv("https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt",
                      names = ['sex', 'length', 'diameter', 'height','whole_weight', 'shucked_weight', 'viscera_weight','shell_weight', 'rings']) #https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt 파일 읽어 옴
print(pd_data.head().T)

성별을 기준으로 rings의 평균을 구해 보자.

print(pd_data.groupby('sex')['rings'].mean()) #sex 묶음 기준이 되는 컬럼,rings 적용받는 컬럼

성별을 기준으로 rings의 평균값을 출력한 모습

- SQL 과 마찬가지로 한개 이상이 column을 묶을 수 있음

print(pd_data.groupby(['필드명1','필드명2'])['rings'].mean())

- group 으로 튜플 형태로 데이터를 그룹화 할 수 있음

grouped = pd_data.groupby('sex')
for i in grouped:
  print(i)

- 특정 그룹만 가져오기 get_group(키)

from pandas import DataFrame,Series
import pandas as pd
import numpy as np


pd_data = pd.read_csv("https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt",
                      names = ['sex', 'length', 'diameter', 'height','whole_weight', 'shucked_weight', 'viscera_weight','shell_weight', 'rings']) #https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt 파일 읽어 옴
#print(pd_data.head().T)
grouped = pd_data.groupby('sex')
print(grouped.get_group('M'))

- Aggregation : 요약된 통계 정보를 추출해 줌

from pandas import DataFrame,Series
import pandas as pd
import numpy as np

pd_data = pd.read_csv("https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt",
                      names = ['sex', 'length', 'diameter', 'height','whole_weight', 'shucked_weight', 'viscera_weight','shell_weight', 'rings']) #https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt 파일 읽어 옴
#print(pd_data.head().T)
grouped = pd_data.groupby('sex')
grouped.agg(sum)

: 각 성별로 합계 요약 정보를 볼 수 있다.

- 여러개의 요약된 통계 정보를 볼 수 있다.

grouped.agg([np.sum,np.mean,np.std])

: 모든 필드에 대해 합계,평균,표준편차를 확인할 수 있다.

grouped['length'].agg([np.sum,np.mean,np.std]) #length 의 합계,평균,표준편차

: length 의 합계,평균,표준편차를 확인할 수 있다.

 

 

- Transformation : 해당 정보를 변환해줌

grouped.transform(lambda x:(x.max())) #각 그룹별 최댓값으로 변경

각 그룹별 최댓값으로 변경하는 예제

 

- Filtration : 특정 정보를 제거하여 보여주는 필터링 기능

from pandas import DataFrame,Series
import pandas as pd
import numpy as np

df = pd.read_csv("https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt",
                      names = ['sex', 'length', 'diameter', 'height','whole_weight', 'shucked_weight', 'viscera_weight','shell_weight', 'rings']) #https://rfriend.tistory.com/attachment/cfile21.uf@99FC50395B825BD92D1949.txt 파일 읽어 옴

df.groupby('sex').filter(lambda x : (x["height"].max()>=1))

: height 의 max 값이 1보다 크거나 같은 그룹의 데이터만 추출하는 예제

 

 


이 문서는 학생들과 함께 딥러닝 공부를 하기 위해 만든 문서이며~

딥러닝 공부 전에 Numpy와 Pandas 의 기본을 알고 머신러닝을 공부하면 대부분의 머신러닝 소스코드들을 바라보는데 이해의 폭이 넓어질 것 같아서 이론 후 실습 전에 Numpy와 Pandas 의 기본 문법들을 정리해 보았습니다.

 

더욱 자세한 내용은 데이터 사이언스 스쿨을 참고하시면 많은 정보를 얻으 실 수 있을것 같습니다.

 

[참고]

https://datascienceschool.net/intro.html

사업자 정보 표시
원당컴퓨터학원 | 기희경 | 인천 서구 당하동 1028-2 장원프라자 502호 | 사업자 등록번호 : 301-96-83080 | TEL : 032-565-5497 | Mail : icon001@naver.com | 통신판매신고번호 : 호 | 사이버몰의 이용약관 바로가기