PYTHON LIBRARY/Numpy & Pandas 실습

Pandas 실습 문제 : 데이터 columns 다루기 및 read(encoding) 사용법과 기초 함수 복습

신강희 2024. 4. 14. 18:53
728x90

# 기초개념에서 배운것들을 실습문제를 통해서 복습

import pandas as pd

 

롤 랭킹 데이터 : https://www.kaggle.com/datasnaek/league-of-legends

DataUrl = ‘https://raw.githubusercontent.com/Datamanim/pandas/main/lol.csv

 

DataUrl = 'https://raw.githubusercontent.com/Datamanim/pandas/main/lol.csv'
df = pd.read_csv(DataUrl, sep='\t')

 

ㄴ pd.read_csv() 함수는 기본적으로 쉼표(,)로 구분된 CSV 파일을 읽는다. 그러나 데이터 파일이 쉼표 외의 다른 구분자(예: 탭, 공백 등)로 구분되어 있다면 sep 인자를 사용하여 해당 구분자를 지정해야 정상적을 불러온다.

만약 데이터 파일이 다른 구분자(예: 세미콜론(;), 공백 등)로 구분되어 있다면 해당 구분자를 sep 인자에 지정해주어야 한다.

 

 

문제) 데이터의 상위 5개 행을 출력하라

 

df.head(5)

 

문제) 데이터의 행과 열의 갯수를 파악하라

 

df.shape

(9621, 13)

 

# 행만

df.shape[0]

9621

 

# 열만

df.shape[1]

13

 

문제) 전체 컬럼을 출력하라

 

df.columns

Index(['id', '일자', '시도명', '읍면동명', '거주인구', '근무인구', '방문인구', '총 유동인구', '평균 속도',
       '평균 소요 시간', '평균 기온', '일강수량', '평균 풍속'],
      dtype='object')

 

# 출력하라고 하였으니 print() 문까지 사용해주는것이 좀더 명확함

print(df.columns)

Index(['id', '일자', '시도명', '읍면동명', '거주인구', '근무인구', '방문인구', '총 유동인구', '평균 속도',
       '평균 소요 시간', '평균 기온', '일강수량', '평균 풍속'],
      dtype='object')

 

문제) 6번째 컬럼명을 출력하라

 

# 데이터의 경우 0에서 부터 인덱스 순서를 매기기 때문에 6번째 컬럼이면 0,1,2,3,4,5 로 5가 여섯번째 이다.

df.columns[5]

'firstBlood'

 

문제) 26번째 컬럼의 데이터 타입을 확인하라

 

# info() 로 간단하게 확인 가능
df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 51490 entries, 0 to 51489
Data columns (total 61 columns):
 #   Column              Non-Null Count  Dtype
---  ------              --------------  -----
 0   gameId              51490 non-null  int64
 1   creationTime        51490 non-null  int64
 2   gameDuration        51490 non-null  int64
 3   seasonId            51490 non-null  int64
 4   winner              51490 non-null  int64
 5   firstBlood          51490 non-null  int64
 6   firstTower          51490 non-null  int64
 7   firstInhibitor      51490 non-null  int64
 8   firstBaron          51490 non-null  int64
 9   firstDragon         51490 non-null  int64
 10  firstRiftHerald     51490 non-null  int64
 11  t1_champ1id         51490 non-null  int64
 12  t1_champ1_sum1      51490 non-null  int64
 13  t1_champ1_sum2      51490 non-null  int64
 14  t1_champ2id         51490 non-null  int64
 15  t1_champ2_sum1      51490 non-null  int64
 16  t1_champ2_sum2      51490 non-null  int64
 17  t1_champ3id         51490 non-null  int64
 18  t1_champ3_sum1      51490 non-null  int64
 19  t1_champ3_sum2      51490 non-null  int64
 20  t1_champ4id         51490 non-null  int64
 21  t1_champ4_sum1      51490 non-null  int64
 22  t1_champ4_sum2      51490 non-null  int64
 23  t1_champ5id         51490 non-null  int64
 24  t1_champ5_sum1      51490 non-null  int64
 25  t1_champ5_sum2      51490 non-null  int64
 26  t1_towerKills       51490 non-null  int64
 27  t1_inhibitorKills   51490 non-null  int64
 28  t1_baronKills       51490 non-null  int64
 29  t1_dragonKills      51490 non-null  int64
 30  t1_riftHeraldKills  51490 non-null  int64
 31  t1_ban1             51490 non-null  int64
 32  t1_ban2             51490 non-null  int64
 33  t1_ban3             51490 non-null  int64
 34  t1_ban4             51490 non-null  int64
 35  t1_ban5             51490 non-null  int64
 36  t2_champ1id         51490 non-null  int64
 37  t2_champ1_sum1      51490 non-null  int64
 38  t2_champ1_sum2      51490 non-null  int64
 39  t2_champ2id         51490 non-null  int64
 40  t2_champ2_sum1      51490 non-null  int64
 41  t2_champ2_sum2      51490 non-null  int64
 42  t2_champ3id         51490 non-null  int64
 43  t2_champ3_sum1      51490 non-null  int64
 44  t2_champ3_sum2      51490 non-null  int64
 45  t2_champ4id         51490 non-null  int64
 46  t2_champ4_sum1      51490 non-null  int64
 47  t2_champ4_sum2      51490 non-null  int64
 48  t2_champ5id         51490 non-null  int64
 49  t2_champ5_sum1      51490 non-null  int64
 50  t2_champ5_sum2      51490 non-null  int64
 51  t2_towerKills       51490 non-null  int64
 52  t2_inhibitorKills   51490 non-null  int64
 53  t2_baronKills       51490 non-null  int64
 54  t2_dragonKills      51490 non-null  int64
 55  t2_riftHeraldKills  51490 non-null  int64
 56  t2_ban1             51490 non-null  int64
 57  t2_ban2             51490 non-null  int64
 58  t2_ban3             51490 non-null  int64
 59  t2_ban4             51490 non-null  int64
 60  t2_ban5             51490 non-null  int64
dtypes: int64(61)
memory usage: 24.0 MB

 

# 특정 컬럼을 불러와서 확인해도 된다.
df.iloc[ : , 25 + 1 ].dtype

dtype('int64')

 

문제) 6번째 컬럼의 3번째 값은 무엇인가?

 

# info로 컬럼을 찾아서 가져온다.

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 51490 entries, 0 to 51489
Data columns (total 61 columns):
 #   Column              Non-Null Count  Dtype
---  ------              --------------  -----
 0   gameId              51490 non-null  int64
 1   creationTime        51490 non-null  int64
 2   gameDuration        51490 non-null  int64
 3   seasonId            51490 non-null  int64
 4   winner              51490 non-null  int64
 5   firstBlood          51490 non-null  int64
 6   firstTower          51490 non-null  int64
 7   firstInhibitor      51490 non-null  int64
 8   firstBaron          51490 non-null  int64
 9   firstDragon         51490 non-null  int64
 10  firstRiftHerald     51490 non-null  int64
 11  t1_champ1id         51490 non-null  int64
 12  t1_champ1_sum1      51490 non-null  int64
 13  t1_champ1_sum2      51490 non-null  int64
 14  t1_champ2id         51490 non-null  int64
 15  t1_champ2_sum1      51490 non-null  int64
 16  t1_champ2_sum2      51490 non-null  int64
 17  t1_champ3id         51490 non-null  int64
 18  t1_champ3_sum1      51490 non-null  int64
 19  t1_champ3_sum2      51490 non-null  int64
 20  t1_champ4id         51490 non-null  int64
 21  t1_champ4_sum1      51490 non-null  int64
 22  t1_champ4_sum2      51490 non-null  int64
 23  t1_champ5id         51490 non-null  int64
 24  t1_champ5_sum1      51490 non-null  int64
 25  t1_champ5_sum2      51490 non-null  int64
 26  t1_towerKills       51490 non-null  int64
 27  t1_inhibitorKills   51490 non-null  int64
 28  t1_baronKills       51490 non-null  int64
 29  t1_dragonKills      51490 non-null  int64
 30  t1_riftHeraldKills  51490 non-null  int64
 31  t1_ban1             51490 non-null  int64
 32  t1_ban2             51490 non-null  int64
 33  t1_ban3             51490 non-null  int64
 34  t1_ban4             51490 non-null  int64
 35  t1_ban5             51490 non-null  int64
 36  t2_champ1id         51490 non-null  int64
 37  t2_champ1_sum1      51490 non-null  int64
 38  t2_champ1_sum2      51490 non-null  int64
 39  t2_champ2id         51490 non-null  int64
 40  t2_champ2_sum1      51490 non-null  int64
 41  t2_champ2_sum2      51490 non-null  int64
 42  t2_champ3id         51490 non-null  int64
 43  t2_champ3_sum1      51490 non-null  int64
 44  t2_champ3_sum2      51490 non-null  int64
 45  t2_champ4id         51490 non-null  int64
 46  t2_champ4_sum1      51490 non-null  int64
 47  t2_champ4_sum2      51490 non-null  int64
 48  t2_champ5id         51490 non-null  int64
 49  t2_champ5_sum1      51490 non-null  int64
 50  t2_champ5_sum2      51490 non-null  int64
 51  t2_towerKills       51490 non-null  int64
 52  t2_inhibitorKills   51490 non-null  int64
 53  t2_baronKills       51490 non-null  int64
 54  t2_dragonKills      51490 non-null  int64
 55  t2_riftHeraldKills  51490 non-null  int64
 56  t2_ban1             51490 non-null  int64
 57  t2_ban2             51490 non-null  int64
 58  t2_ban3             51490 non-null  int64
 59  t2_ban4             51490 non-null  int64
 60  t2_ban5             51490 non-null  int64
dtypes: int64(61)
memory usage: 24.0 MB

 

# 6번쨰 컬럼이 firstBlood인걸 확인했으니 거기서 세번쨰 0,1,2 순서로 [2] 데이터를 가져와라

df['firstBlood'][2]

2

 

## loc 혹은 iloc를 활용하여 행,열자체를 지정해서 가져와도 된다. ##

 

<새로운 데이터로 다음 실습문제 풀이>

 

제주 날씨,인구에 따른 교통량데이터 : 출처 제주 데이터 허브

DataUrl = ‘https://raw.githubusercontent.com/Datamanim/pandas/main/Jeju.csv

 

DataUrl = 'https://raw.githubusercontent.com/Datamanim/pandas/main/Jeju.csv'
df = pd.read_csv(DataUrl, encoding='euc-kr')

ㄴ 이파일은 ecu-kr 형태로 인코딩 되어있다는 뜻

ㄴ 기본적으로 UTF-8 로 인코딩 되어있지만 특정 형태로 인코딩 되어있을경우 encoding 설정을 해주어야 데이터를 정상적으로 불러온다.

 

문제) 데이터 마지막 3개행을 출력하라

 

df.tail(3)

 

문제) 이 데이터는 몇일치 날짜 데이터로 되어있나??

 

df['일자'].nunique()

803

 

문제) 각 컬럼의 결측치(NaN) 숫자를 파악하라

 

df.isna().sum()

id          0
일자          0
시도명         0
읍면동명        0
거주인구        0
근무인구        0
방문인구        0
총 유동인구      0
평균 속도       0
평균 소요 시간    0
평균 기온       0
일강수량        0
평균 풍속       0
dtype: int64

 

문제)  수치형 변수의 분포(사분위, 평균, 표준편차, 최대 , 최소)를 확인하라

 

# 각 수치형 변수란 컬럼을 뜻한다.
df.describe()

 

문제) 읍면동명 컬럼의 유일값 갯수를 출력하라

 

df['읍면동명'].nunique()

41

 

문제) 읍면동명 컬럼의 유일값을 모두 출력하라 

 

df['읍면동명'].unique()

array(['도두동', '외도동', '이도2동', '일도1동', '대천동', '서홍동', '한경면', '송산동', '조천읍',
       '일도2동', '영천동', '예래동', '대륜동', '삼도1동', '이호동', '건입동', '중앙동', '삼양동',
       '삼도2동', '이도1동', '남원읍', '대정읍', '정방동', '효돈동', '아라동', '한림읍', '구좌읍',
       '용담1동', '오라동', '화북동', '연동', '표선면', '중문동', '성산읍', '안덕면', '천지동',
       '노형동', '동홍동', '용담2동', '봉개동', '애월읍'], dtype=object)

 

다음 실습 문제로 계속

반응형