728x90
Pandas 연습 문제 풀기 -8 🐼
In [1]:
# 라이브러리 임포트
import pandas as pd
데이터 알아보기¶
In [2]:
import os
os.listdir('./data')
Out[2]:
['2014-baby-names-illinois.csv',
'2015-baby-names-illinois.csv',
'billboard.csv',
'country_timeseries.csv',
'nav_2018.csv',
'pew.csv',
'stock price.xlsx',
'stock valuation.xlsx',
'tb-raw.csv',
'titles.csv',
'weather.csv']
In [3]:
# 파일 './data/nav_2018.csv'를 encoding='utf-8'으로 불러와서 df대입
df = pd.read_csv('./data/nav_2018.csv', encoding='utf-8', index_col=0)
df
Out[3]:
Date | Start (ET) | Visitor/Neutral | PTS | Home/Neutral | PTS.1 | .1 | Attend. | Notes | ||
---|---|---|---|---|---|---|---|---|---|---|
0 | Tue, Oct 17, 2017 | 8:01p | Boston Celtics | 99 | Cleveland Cavaliers | 102 | Box Score | NaN | 20562 | NaN |
1 | Tue, Oct 17, 2017 | 10:30p | Houston Rockets | 122 | Golden State Warriors | 121 | Box Score | NaN | 19596 | NaN |
2 | Wed, Oct 18, 2017 | 7:30p | Milwaukee Bucks | 108 | Boston Celtics | 100 | Box Score | NaN | 18624 | NaN |
3 | Wed, Oct 18, 2017 | 8:30p | Atlanta Hawks | 117 | Dallas Mavericks | 111 | Box Score | NaN | 19709 | NaN |
4 | Wed, Oct 18, 2017 | 7:00p | Charlotte Hornets | 90 | Detroit Pistons | 102 | Box Score | NaN | 20491 | NaN |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
99 | Mon, Oct 30, 2017 | 9:00p | Dallas Mavericks | 89 | Utah Jazz | 104 | Box Score | NaN | 16221 | NaN |
100 | Tue, Oct 31, 2017 | 7:30p | Phoenix Suns | 122 | Brooklyn Nets | 114 | Box Score | NaN | 12936 | NaN |
101 | Tue, Oct 31, 2017 | 7:00p | Sacramento Kings | 83 | Indiana Pacers | 101 | Box Score | NaN | 12245 | NaN |
102 | Tue, Oct 31, 2017 | 10:30p | Detroit Pistons | 93 | Los Angeles Lakers | 113 | Box Score | NaN | 17569 | NaN |
103 | Tue, Oct 31, 2017 | 8:00p | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 | Box Score | NaN | 16713 | NaN |
104 rows × 10 columns
In [4]:
# 요약 정보확인
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 104 entries, 0 to 103
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 104 non-null object
1 Start (ET) 104 non-null object
2 Visitor/Neutral 104 non-null object
3 PTS 104 non-null int64
4 Home/Neutral 104 non-null object
5 PTS.1 104 non-null int64
6 104 non-null object
7 .1 2 non-null object
8 Attend. 104 non-null int64
9 Notes 0 non-null float64
dtypes: float64(1), int64(3), object(6)
memory usage: 8.9+ KB
In [5]:
# 행,열
df.shape
Out[5]:
(104, 10)
In [6]:
# 앞 5개 데이터 보기
df.head()
Out[6]:
Date | Start (ET) | Visitor/Neutral | PTS | Home/Neutral | PTS.1 | .1 | Attend. | Notes | ||
---|---|---|---|---|---|---|---|---|---|---|
0 | Tue, Oct 17, 2017 | 8:01p | Boston Celtics | 99 | Cleveland Cavaliers | 102 | Box Score | NaN | 20562 | NaN |
1 | Tue, Oct 17, 2017 | 10:30p | Houston Rockets | 122 | Golden State Warriors | 121 | Box Score | NaN | 19596 | NaN |
2 | Wed, Oct 18, 2017 | 7:30p | Milwaukee Bucks | 108 | Boston Celtics | 100 | Box Score | NaN | 18624 | NaN |
3 | Wed, Oct 18, 2017 | 8:30p | Atlanta Hawks | 117 | Dallas Mavericks | 111 | Box Score | NaN | 19709 | NaN |
4 | Wed, Oct 18, 2017 | 7:00p | Charlotte Hornets | 90 | Detroit Pistons | 102 | Box Score | NaN | 20491 | NaN |
데이터 자료형 및 이름 맞추기¶
In [7]:
# 컬럼 확인
df.columns
Out[7]:
Index(['Date', 'Start (ET)', 'Visitor/Neutral', 'PTS', 'Home/Neutral', 'PTS.1',
' ', ' .1', 'Attend.', 'Notes'],
dtype='object')
In [8]:
# 6번째 컬럼확인
df.columns[5]
Out[8]:
'PTS.1'
In [9]:
# 7번째 컬럼 확인
df.columns[6]
Out[9]:
'\xa0'
In [10]:
# 변경할 컬럼이름 세팅해서 column_names에 대입
column_names = ["경기일자","start","방문팀","방문팀점수","홈팀","홈팀점수","Box","n_ot","관중수","Notes"]
column_names
Out[10]:
['경기일자', 'start', '방문팀', '방문팀점수', '홈팀', '홈팀점수', 'Box', 'n_ot', '관중수', 'Notes']
In [11]:
# df컬럼명 변경
df.columns = column_names
df
Out[11]:
경기일자 | start | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | Box | n_ot | 관중수 | Notes | |
---|---|---|---|---|---|---|---|---|---|---|
0 | Tue, Oct 17, 2017 | 8:01p | Boston Celtics | 99 | Cleveland Cavaliers | 102 | Box Score | NaN | 20562 | NaN |
1 | Tue, Oct 17, 2017 | 10:30p | Houston Rockets | 122 | Golden State Warriors | 121 | Box Score | NaN | 19596 | NaN |
2 | Wed, Oct 18, 2017 | 7:30p | Milwaukee Bucks | 108 | Boston Celtics | 100 | Box Score | NaN | 18624 | NaN |
3 | Wed, Oct 18, 2017 | 8:30p | Atlanta Hawks | 117 | Dallas Mavericks | 111 | Box Score | NaN | 19709 | NaN |
4 | Wed, Oct 18, 2017 | 7:00p | Charlotte Hornets | 90 | Detroit Pistons | 102 | Box Score | NaN | 20491 | NaN |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
99 | Mon, Oct 30, 2017 | 9:00p | Dallas Mavericks | 89 | Utah Jazz | 104 | Box Score | NaN | 16221 | NaN |
100 | Tue, Oct 31, 2017 | 7:30p | Phoenix Suns | 122 | Brooklyn Nets | 114 | Box Score | NaN | 12936 | NaN |
101 | Tue, Oct 31, 2017 | 7:00p | Sacramento Kings | 83 | Indiana Pacers | 101 | Box Score | NaN | 12245 | NaN |
102 | Tue, Oct 31, 2017 | 10:30p | Detroit Pistons | 93 | Los Angeles Lakers | 113 | Box Score | NaN | 17569 | NaN |
103 | Tue, Oct 31, 2017 | 8:00p | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 | Box Score | NaN | 16713 | NaN |
104 rows × 10 columns
In [12]:
# df에 변경내용 대입
# 벌써 위에서 대입해버림... ㅋㅋㅋㅋ
In [13]:
# 변경된 컬럼명 확인
df.columns
Out[13]:
Index(['경기일자', 'start', '방문팀', '방문팀점수', '홈팀', '홈팀점수', 'Box', 'n_ot', '관중수',
'Notes'],
dtype='object')
In [14]:
# 앞 5개 데이터 보기
df.head()
Out[14]:
경기일자 | start | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | Box | n_ot | 관중수 | Notes | |
---|---|---|---|---|---|---|---|---|---|---|
0 | Tue, Oct 17, 2017 | 8:01p | Boston Celtics | 99 | Cleveland Cavaliers | 102 | Box Score | NaN | 20562 | NaN |
1 | Tue, Oct 17, 2017 | 10:30p | Houston Rockets | 122 | Golden State Warriors | 121 | Box Score | NaN | 19596 | NaN |
2 | Wed, Oct 18, 2017 | 7:30p | Milwaukee Bucks | 108 | Boston Celtics | 100 | Box Score | NaN | 18624 | NaN |
3 | Wed, Oct 18, 2017 | 8:30p | Atlanta Hawks | 117 | Dallas Mavericks | 111 | Box Score | NaN | 19709 | NaN |
4 | Wed, Oct 18, 2017 | 7:00p | Charlotte Hornets | 90 | Detroit Pistons | 102 | Box Score | NaN | 20491 | NaN |
In [15]:
# '경기일자' 열의 데이터 타입확인
df.경기일자.dtype
Out[15]:
dtype('O')
In [16]:
# 'Tue, Oct 17, 2017'의 문자열 데이터를 datetime타입으로 변경
pd.to_datetime('Tue, Oct 17, 2017', format='%a, %b %d, %Y')
Out[16]:
Timestamp('2017-10-17 00:00:00')
In [17]:
# '경기일자' 열의 데이터 타입을 위에 내용을 보고 datetime타입으로 변경에 다시 '경기일자'열에 대입한다.
pd.to_datetime(df.경기일자, format='%a, %b %d, %Y')
Out[17]:
0 2017-10-17
1 2017-10-17
2 2017-10-18
3 2017-10-18
4 2017-10-18
...
99 2017-10-30
100 2017-10-31
101 2017-10-31
102 2017-10-31
103 2017-10-31
Name: 경기일자, Length: 104, dtype: datetime64[ns]
In [18]:
df.경기일자 = pd.to_datetime(df.경기일자, format='%a, %b %d, %Y')
In [19]:
# '경기일자' 열의 데이터 타입확인
df.경기일자.dtypes
Out[19]:
dtype('<M8[ns]')
In [20]:
# df.head()
df.head()
Out[20]:
경기일자 | start | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | Box | n_ot | 관중수 | Notes | |
---|---|---|---|---|---|---|---|---|---|---|
0 | 2017-10-17 | 8:01p | Boston Celtics | 99 | Cleveland Cavaliers | 102 | Box Score | NaN | 20562 | NaN |
1 | 2017-10-17 | 10:30p | Houston Rockets | 122 | Golden State Warriors | 121 | Box Score | NaN | 19596 | NaN |
2 | 2017-10-18 | 7:30p | Milwaukee Bucks | 108 | Boston Celtics | 100 | Box Score | NaN | 18624 | NaN |
3 | 2017-10-18 | 8:30p | Atlanta Hawks | 117 | Dallas Mavericks | 111 | Box Score | NaN | 19709 | NaN |
4 | 2017-10-18 | 7:00p | Charlotte Hornets | 90 | Detroit Pistons | 102 | Box Score | NaN | 20491 | NaN |
초기값 및 결측데이터 정리하기¶
In [21]:
# df의 결측치 개수 구하기
df.isnull().sum()
Out[21]:
경기일자 0
start 0
방문팀 0
방문팀점수 0
홈팀 0
홈팀점수 0
Box 0
n_ot 102
관중수 0
Notes 104
dtype: int64
In [22]:
# 'n_ot'의 유효데이터 보기
df[df.n_ot.notnull()]
Out[22]:
경기일자 | start | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | Box | n_ot | 관중수 | Notes | |
---|---|---|---|---|---|---|---|---|---|---|
59 | 2017-10-25 | 10:30p | Washington Wizards | 99 | Los Angeles Lakers | 102 | Box Score | OT | 18996 | NaN |
95 | 2017-10-30 | 7:30p | Minnesota Timberwolves | 125 | Miami Heat | 122 | Box Score | OT | 19600 | NaN |
In [23]:
# 'n_ot'열의 결측치를 'NOT'로 변경하기
df.n_ot = df.n_ot.fillna("NOT")
In [24]:
df.n_ot.isnull().sum()
Out[24]:
0
In [25]:
# 'n_ot'열의 고유데이터 수 구하기
df.n_ot.value_counts()
Out[25]:
NOT 102
OT 2
Name: n_ot, dtype: int64
In [26]:
# df.info()
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 104 entries, 0 to 103
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 경기일자 104 non-null datetime64[ns]
1 start 104 non-null object
2 방문팀 104 non-null object
3 방문팀점수 104 non-null int64
4 홈팀 104 non-null object
5 홈팀점수 104 non-null int64
6 Box 104 non-null object
7 n_ot 104 non-null object
8 관중수 104 non-null int64
9 Notes 0 non-null float64
dtypes: datetime64[ns](1), float64(1), int64(3), object(5)
memory usage: 8.9+ KB
In [27]:
df.isnull().sum()
Out[27]:
경기일자 0
start 0
방문팀 0
방문팀점수 0
홈팀 0
홈팀점수 0
Box 0
n_ot 0
관중수 0
Notes 104
dtype: int64
In [28]:
# 결측치가 많은 'Notes'열 삭제
df.drop(columns="Notes", inplace=True)
In [29]:
# df
df
Out[29]:
경기일자 | start | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | Box | n_ot | 관중수 | |
---|---|---|---|---|---|---|---|---|---|
0 | 2017-10-17 | 8:01p | Boston Celtics | 99 | Cleveland Cavaliers | 102 | Box Score | NOT | 20562 |
1 | 2017-10-17 | 10:30p | Houston Rockets | 122 | Golden State Warriors | 121 | Box Score | NOT | 19596 |
2 | 2017-10-18 | 7:30p | Milwaukee Bucks | 108 | Boston Celtics | 100 | Box Score | NOT | 18624 |
3 | 2017-10-18 | 8:30p | Atlanta Hawks | 117 | Dallas Mavericks | 111 | Box Score | NOT | 19709 |
4 | 2017-10-18 | 7:00p | Charlotte Hornets | 90 | Detroit Pistons | 102 | Box Score | NOT | 20491 |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
99 | 2017-10-30 | 9:00p | Dallas Mavericks | 89 | Utah Jazz | 104 | Box Score | NOT | 16221 |
100 | 2017-10-31 | 7:30p | Phoenix Suns | 122 | Brooklyn Nets | 114 | Box Score | NOT | 12936 |
101 | 2017-10-31 | 7:00p | Sacramento Kings | 83 | Indiana Pacers | 101 | Box Score | NOT | 12245 |
102 | 2017-10-31 | 10:30p | Detroit Pistons | 93 | Los Angeles Lakers | 113 | Box Score | NOT | 17569 |
103 | 2017-10-31 | 8:00p | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 | Box Score | NOT | 16713 |
104 rows × 9 columns
필요 열만 추출해서 정리하기¶
In [30]:
# ['경기일자', '방문팀', '방문팀점수', '홈팀', '홈팀점수']열만 추출해서 df_sub에 대입
df_sub = df[['경기일자', '방문팀', '방문팀점수', '홈팀', '홈팀점수']]
In [31]:
# df_sub 컬럼확인
df_sub.columns
Out[31]:
Index(['경기일자', '방문팀', '방문팀점수', '홈팀', '홈팀점수'], dtype='object')
In [32]:
# df_sub.head()
df_sub.head()
Out[32]:
경기일자 | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | |
---|---|---|---|---|---|
0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 |
1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 |
2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 |
3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 |
4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 |
In [33]:
# df_sub의 '경기일자'열을 인덱스로 설정 append=True옵션 적용하여 기존 인덱스 유지
df_sub = df_sub.set_index("경기일자",append=True)
In [34]:
# df_sub
df_sub
Out[34]:
방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | ||
---|---|---|---|---|---|
경기일자 | |||||
0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 |
1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 |
2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 |
3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 |
4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 |
... | ... | ... | ... | ... | ... |
99 | 2017-10-30 | Dallas Mavericks | 89 | Utah Jazz | 104 |
100 | 2017-10-31 | Phoenix Suns | 122 | Brooklyn Nets | 114 |
101 | 2017-10-31 | Sacramento Kings | 83 | Indiana Pacers | 101 |
102 | 2017-10-31 | Detroit Pistons | 93 | Los Angeles Lakers | 113 |
103 | 2017-10-31 | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 |
104 rows × 4 columns
In [35]:
# df_sub의 인덱스 이름을 ['게임', '경기일자']로 변경. rename_axis()
df_sub.rename_axis(['게임', '경기일자'],inplace=True)
In [36]:
# df_sub
df_sub
Out[36]:
방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | ||
---|---|---|---|---|---|
게임 | 경기일자 | ||||
0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 |
1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 |
2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 |
3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 |
4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 |
... | ... | ... | ... | ... | ... |
99 | 2017-10-30 | Dallas Mavericks | 89 | Utah Jazz | 104 |
100 | 2017-10-31 | Phoenix Suns | 122 | Brooklyn Nets | 114 |
101 | 2017-10-31 | Sacramento Kings | 83 | Indiana Pacers | 101 |
102 | 2017-10-31 | Detroit Pistons | 93 | Los Angeles Lakers | 113 |
103 | 2017-10-31 | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 |
104 rows × 4 columns
In [37]:
# df_sub인덱스 확인
df_sub.index
Out[37]:
MultiIndex([( 0, '2017-10-17'),
( 1, '2017-10-17'),
( 2, '2017-10-18'),
( 3, '2017-10-18'),
( 4, '2017-10-18'),
( 5, '2017-10-18'),
( 6, '2017-10-18'),
( 7, '2017-10-18'),
( 8, '2017-10-18'),
( 9, '2017-10-18'),
...
( 94, '2017-10-30'),
( 95, '2017-10-30'),
( 96, '2017-10-30'),
( 97, '2017-10-30'),
( 98, '2017-10-30'),
( 99, '2017-10-30'),
(100, '2017-10-31'),
(101, '2017-10-31'),
(102, '2017-10-31'),
(103, '2017-10-31')],
names=['게임', '경기일자'], length=104)
In [38]:
# df_sub의 인덱스를 정렬해서 df_sub에 대입
df_sub.sort_index(inplace=True)
데이터 조정해서 확정하기¶
In [39]:
# df_sub
df_sub
Out[39]:
방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | ||
---|---|---|---|---|---|
게임 | 경기일자 | ||||
0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 |
1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 |
2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 |
3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 |
4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 |
... | ... | ... | ... | ... | ... |
99 | 2017-10-30 | Dallas Mavericks | 89 | Utah Jazz | 104 |
100 | 2017-10-31 | Phoenix Suns | 122 | Brooklyn Nets | 114 |
101 | 2017-10-31 | Sacramento Kings | 83 | Indiana Pacers | 101 |
102 | 2017-10-31 | Detroit Pistons | 93 | Los Angeles Lakers | 113 |
103 | 2017-10-31 | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 |
104 rows × 4 columns
In [40]:
# df_sub의 인덱스를 reset한다.
df_sub.reset_index(inplace=True)
In [41]:
# df_sub
df_sub
Out[41]:
게임 | 경기일자 | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | |
---|---|---|---|---|---|---|
0 | 0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 |
1 | 1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 |
2 | 2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 |
3 | 3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 |
4 | 4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 |
... | ... | ... | ... | ... | ... | ... |
99 | 99 | 2017-10-30 | Dallas Mavericks | 89 | Utah Jazz | 104 |
100 | 100 | 2017-10-31 | Phoenix Suns | 122 | Brooklyn Nets | 114 |
101 | 101 | 2017-10-31 | Sacramento Kings | 83 | Indiana Pacers | 101 |
102 | 102 | 2017-10-31 | Detroit Pistons | 93 | Los Angeles Lakers | 113 |
103 | 103 | 2017-10-31 | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 |
104 rows × 6 columns
In [47]:
# '방문팀', '홈팀'을 하나의 열의 데이터로 melt한다.
# '게임', '경기일자'열은 남겨두고 '방문팀', '홈팀'을 value로 세팅한다.
# 새로생성되는 변수이름은 '팀구분'
# 새로생성되는 value이름은 '팀'으로 한다.
# metl한 결과를 tidy 변수에 대입한다.
In [48]:
tidy = pd.melt(df_sub, id_vars=['게임', '경기일자'],value_vars=['방문팀', '홈팀'], var_name="팀구분", value_name="팀")
In [49]:
# tidy.info()
tidy.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 208 entries, 0 to 207
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 게임 208 non-null int64
1 경기일자 208 non-null datetime64[ns]
2 팀구분 208 non-null object
3 팀 208 non-null object
dtypes: datetime64[ns](1), int64(1), object(2)
memory usage: 6.6+ KB
In [50]:
# tidy.head()
tidy.head()
Out[50]:
게임 | 경기일자 | 팀구분 | 팀 | |
---|---|---|---|---|
0 | 0 | 2017-10-17 | 방문팀 | Boston Celtics |
1 | 1 | 2017-10-17 | 방문팀 | Houston Rockets |
2 | 2 | 2017-10-18 | 방문팀 | Milwaukee Bucks |
3 | 3 | 2017-10-18 | 방문팀 | Atlanta Hawks |
4 | 4 | 2017-10-18 | 방문팀 | Charlotte Hornets |
In [51]:
# tidy.tail()
tidy.tail()
Out[51]:
게임 | 경기일자 | 팀구분 | 팀 | |
---|---|---|---|---|
203 | 99 | 2017-10-30 | 홈팀 | Utah Jazz |
204 | 100 | 2017-10-31 | 홈팀 | Brooklyn Nets |
205 | 101 | 2017-10-31 | 홈팀 | Indiana Pacers |
206 | 102 | 2017-10-31 | 홈팀 | Los Angeles Lakers |
207 | 103 | 2017-10-31 | 홈팀 | Milwaukee Bucks |
In [52]:
# tidy의 '경기일자'열의 데이터타입 확인
tidy.경기일자.dtypes
Out[52]:
dtype('<M8[ns]')
In [53]:
# (1) tidy를 '팀별' 경기일자를 확인 한다.
tidy.groupby('팀').경기일자.value_counts()
Out[53]:
팀 경기일자
Atlanta Hawks 2017-10-18 1
2017-10-20 1
2017-10-22 1
2017-10-23 1
2017-10-26 1
..
Washington Wizards 2017-10-20 1
2017-10-23 1
2017-10-25 1
2017-10-27 1
2017-10-29 1
Name: 경기일자, Length: 208, dtype: int64
In [54]:
# (2) 팀별 휴식일을 계산하기 위해 위 결과의 경기일자 열에서 다음 행과의 날짜 계산을 한다.
# (현재행의 날짜에서 다음행의 날짜까지 며칠 남았는지 계산)
# 즉, 팀별로 다음 경기까지 며칠이 남았는지 날짜의 차이(diff)를 구한다.
tidy.groupby('팀').경기일자.diff()
Out[54]:
0 NaT
1 NaT
2 NaT
3 NaT
4 NaT
...
203 2 days
204 2 days
205 2 days
206 4 days
207 5 days
Name: 경기일자, Length: 208, dtype: timedelta64[ns]
In [55]:
# (3) 팀별 휴식일을 계산하기 위해 위 결과에서 계산된 날짜 데이터(숫자)만 추출한다.
tidy.groupby('팀').경기일자.diff().dt.days
Out[55]:
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
...
203 2.0
204 2.0
205 2.0
206 4.0
207 5.0
Name: 경기일자, Length: 208, dtype: float64
In [56]:
# (4) 팀별 휴식일을 계산하기 위해 위 결과에서 추출된 날짜(숫자)에서 1을 뺀다.
# 다음 경기와의 날짜가 1일 남았다는 건 휴식일이 없다(다음날 바로 경기가 있으므로)는 것이므로
# 다음 경기까지 남은 날짜에서 - 1을 해서 휴식일을 구한다.
tidy.groupby('팀').경기일자.diff().dt.days - 1
Out[56]:
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
...
203 1.0
204 1.0
205 1.0
206 3.0
207 4.0
Name: 경기일자, Length: 208, dtype: float64
In [58]:
# 위 (1)-(4)까지의 과정을 실해해서 tidy에 '휴식일'열을 새로 생성해서 대입한다.
tidy.sort_values('경기일자').groupby('팀').경기일자.diff().dt.days - 1
Out[58]:
0 NaN
1 NaN
104 NaN
105 NaN
109 NaN
...
102 1.0
101 1.0
100 2.0
206 2.0
207 1.0
Name: 경기일자, Length: 208, dtype: float64
In [59]:
tidy["휴식일"] = tidy.sort_values('경기일자').groupby('팀').경기일자.diff().dt.days - 1
In [60]:
# tidy
tidy
Out[60]:
게임 | 경기일자 | 팀구분 | 팀 | 휴식일 | |
---|---|---|---|---|---|
0 | 0 | 2017-10-17 | 방문팀 | Boston Celtics | NaN |
1 | 1 | 2017-10-17 | 방문팀 | Houston Rockets | NaN |
2 | 2 | 2017-10-18 | 방문팀 | Milwaukee Bucks | NaN |
3 | 3 | 2017-10-18 | 방문팀 | Atlanta Hawks | NaN |
4 | 4 | 2017-10-18 | 방문팀 | Charlotte Hornets | NaN |
... | ... | ... | ... | ... | ... |
203 | 99 | 2017-10-30 | 홈팀 | Utah Jazz | 1.0 |
204 | 100 | 2017-10-31 | 홈팀 | Brooklyn Nets | 1.0 |
205 | 101 | 2017-10-31 | 홈팀 | Indiana Pacers | 1.0 |
206 | 102 | 2017-10-31 | 홈팀 | Los Angeles Lakers | 2.0 |
207 | 103 | 2017-10-31 | 홈팀 | Milwaukee Bucks | 1.0 |
208 rows × 5 columns
In [61]:
# tidy의 결측치 데이터수를 계산한다.
tidy.isnull().sum()
Out[61]:
게임 0
경기일자 0
팀구분 0
팀 0
휴식일 30
dtype: int64
In [68]:
# 결측치를 0으로 채운다.
tidy.fillna(0,inplace=True)
tidy
Out[68]:
게임 | 경기일자 | 팀구분 | 팀 | 휴식일 | |
---|---|---|---|---|---|
0 | 0 | 2017-10-17 | 방문팀 | Boston Celtics | 0.0 |
1 | 1 | 2017-10-17 | 방문팀 | Houston Rockets | 0.0 |
2 | 2 | 2017-10-18 | 방문팀 | Milwaukee Bucks | 0.0 |
3 | 3 | 2017-10-18 | 방문팀 | Atlanta Hawks | 0.0 |
4 | 4 | 2017-10-18 | 방문팀 | Charlotte Hornets | 0.0 |
... | ... | ... | ... | ... | ... |
203 | 99 | 2017-10-30 | 홈팀 | Utah Jazz | 1.0 |
204 | 100 | 2017-10-31 | 홈팀 | Brooklyn Nets | 1.0 |
205 | 101 | 2017-10-31 | 홈팀 | Indiana Pacers | 1.0 |
206 | 102 | 2017-10-31 | 홈팀 | Los Angeles Lakers | 2.0 |
207 | 103 | 2017-10-31 | 홈팀 | Milwaukee Bucks | 1.0 |
208 rows × 5 columns
In [69]:
# 행,열확인
tidy.shape
Out[69]:
(208, 5)
In [70]:
# tidy.head()
tidy.head()
Out[70]:
게임 | 경기일자 | 팀구분 | 팀 | 휴식일 | |
---|---|---|---|---|---|
0 | 0 | 2017-10-17 | 방문팀 | Boston Celtics | 0.0 |
1 | 1 | 2017-10-17 | 방문팀 | Houston Rockets | 0.0 |
2 | 2 | 2017-10-18 | 방문팀 | Milwaukee Bucks | 0.0 |
3 | 3 | 2017-10-18 | 방문팀 | Atlanta Hawks | 0.0 |
4 | 4 | 2017-10-18 | 방문팀 | Charlotte Hornets | 0.0 |
In [72]:
# '게임','경기일자'를 인덱스로, '팀구분'을 컬럼으로 휴식일을 values로 세팅하고 피벗테이블을 만든다.
# 만들어지 피벗테이블을 by_game에 대입한다.
by_game = pd.pivot_table(tidy, index=['게임','경기일자'], columns="팀구분", values="휴식일")
In [73]:
# by_game.head()
by_game
Out[73]:
팀구분 | 방문팀 | 홈팀 | |
---|---|---|---|
게임 | 경기일자 | ||
0 | 2017-10-17 | 0.0 | 0.0 |
1 | 2017-10-17 | 0.0 | 0.0 |
2 | 2017-10-18 | 0.0 | 0.0 |
3 | 2017-10-18 | 0.0 | 0.0 |
4 | 2017-10-18 | 0.0 | 0.0 |
... | ... | ... | ... |
99 | 2017-10-30 | 1.0 | 1.0 |
100 | 2017-10-31 | 2.0 | 1.0 |
101 | 2017-10-31 | 1.0 | 1.0 |
102 | 2017-10-31 | 1.0 | 2.0 |
103 | 2017-10-31 | 2.0 | 1.0 |
104 rows × 2 columns
In [75]:
# by_game의 컬럼명을 '방문팀'-> '방문팀휴식일', '홈팀'->'홈팀휴식일'로 변경한다.
by_game.columns = ["방문팀휴식일","홈팀휴식일"]
In [76]:
# by_game.head()
by_game.head()
Out[76]:
방문팀휴식일 | 홈팀휴식일 | ||
---|---|---|---|
게임 | 경기일자 | ||
0 | 2017-10-17 | 0.0 | 0.0 |
1 | 2017-10-17 | 0.0 | 0.0 |
2 | 2017-10-18 | 0.0 | 0.0 |
3 | 2017-10-18 | 0.0 | 0.0 |
4 | 2017-10-18 | 0.0 | 0.0 |
In [77]:
# by_game 행,열
by_game.shape
Out[77]:
(104, 2)
In [78]:
# df_sub.head()
df_sub.head()
Out[78]:
게임 | 경기일자 | 방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | |
---|---|---|---|---|---|---|
0 | 0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 |
1 | 1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 |
2 | 2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 |
3 | 3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 |
4 | 4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 |
In [79]:
# df_sub의 인덱스를 '게임', '경기일자'열로 설정
df_sub.set_index(['게임', '경기일자'],inplace=True)
df_sub
Out[79]:
방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | ||
---|---|---|---|---|---|
게임 | 경기일자 | ||||
0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 |
1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 |
2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 |
3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 |
4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 |
... | ... | ... | ... | ... | ... |
99 | 2017-10-30 | Dallas Mavericks | 89 | Utah Jazz | 104 |
100 | 2017-10-31 | Phoenix Suns | 122 | Brooklyn Nets | 114 |
101 | 2017-10-31 | Sacramento Kings | 83 | Indiana Pacers | 101 |
102 | 2017-10-31 | Detroit Pistons | 93 | Los Angeles Lakers | 113 |
103 | 2017-10-31 | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 |
104 rows × 4 columns
In [80]:
# df_sub와 by_geme을 좌우 열방향으로 연결한다.
# 최종 연결된 데이터프레임을 df_fianl에 대입한다.
df_final = pd.concat([df_sub,by_game], axis=1)
In [81]:
# df_final.head()
df_final.head()
Out[81]:
방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | 방문팀휴식일 | 홈팀휴식일 | ||
---|---|---|---|---|---|---|---|
게임 | 경기일자 | ||||||
0 | 2017-10-17 | Boston Celtics | 99 | Cleveland Cavaliers | 102 | 0.0 | 0.0 |
1 | 2017-10-17 | Houston Rockets | 122 | Golden State Warriors | 121 | 0.0 | 0.0 |
2 | 2017-10-18 | Milwaukee Bucks | 108 | Boston Celtics | 100 | 0.0 | 0.0 |
3 | 2017-10-18 | Atlanta Hawks | 117 | Dallas Mavericks | 111 | 0.0 | 0.0 |
4 | 2017-10-18 | Charlotte Hornets | 90 | Detroit Pistons | 102 | 0.0 | 0.0 |
In [82]:
# df_final.tail()
df_final.tail()
Out[82]:
방문팀 | 방문팀점수 | 홈팀 | 홈팀점수 | 방문팀휴식일 | 홈팀휴식일 | ||
---|---|---|---|---|---|---|---|
게임 | 경기일자 | ||||||
99 | 2017-10-30 | Dallas Mavericks | 89 | Utah Jazz | 104 | 1.0 | 1.0 |
100 | 2017-10-31 | Phoenix Suns | 122 | Brooklyn Nets | 114 | 2.0 | 1.0 |
101 | 2017-10-31 | Sacramento Kings | 83 | Indiana Pacers | 101 | 1.0 | 1.0 |
102 | 2017-10-31 | Detroit Pistons | 93 | Los Angeles Lakers | 113 | 1.0 | 2.0 |
103 | 2017-10-31 | Oklahoma City Thunder | 110 | Milwaukee Bucks | 91 | 2.0 | 1.0 |
In [83]:
# df_final 행열
df_final.shape
Out[83]:
(104, 6)
In [84]:
# df_final의 결측치 수
df_final.isnull().sum()
Out[84]:
방문팀 0
방문팀점수 0
홈팀 0
홈팀점수 0
방문팀휴식일 0
홈팀휴식일 0
dtype: int64
github 코드저장소 👉 https://github.com/LIMSONA/KDT/blob/main/pandas/Day_4/%EC%97%B0%EC%8A%B508.ipynb
728x90
'😁 빅데이터 문제 풀기 & Study > - 이외 사이트 문제' 카테고리의 다른 글
[Pandas] Pandas 연습 문제 풀기 -9 🐼 (시각화 중심-Seaborn, groupby, pivot_table 등) (0) | 2022.02.28 |
---|---|
[Pandas] Pandas 연습 문제 풀기 -7 🐼 (0) | 2022.02.24 |
[Pandas] Pandas 연습 문제 풀기 -6 🐼 (0) | 2022.02.23 |
[Pandas] Pandas 연습 문제 풀기 -5 🐼 (0) | 2022.02.23 |
[Pandas] Pandas 연습 문제 풀기 -4 🐼 (0) | 2022.02.22 |