[Python]Pandas를 배우는 Kee

import pandas as pd

by 곰백열두마리

파이썬을 배웁니다.

그리고 연습장이자 꾸준한 공부를 위해서, 불편하지만 브런치에 글을 써보려고 합니다.


연습을 위한 데이터는 Kaggle의 Predict FIFA 2018 Man of the Match입니다.


pandas와 파일을 불러오기

import pandas as pd
data = pd.read_csv("FIFA_2018_Statistics.csv")
data.head()
20190723142021.png


어떤 Columns이 있는지 확인 .columns

data.columns
Index(['Date', 'Team', 'Opponent', 'Goal Scored', 'Ball Possession %', 'Attempts', 'On-Target', 'Off-Target', 'Blocked', 'Corners', 'Offsides', 'Free Kicks', 'Saves', 'Pass Accuracy %', 'Passes', 'Distance Covered (Kms)', 'Fouls Committed', 'Yellow Card', 'Yellow & Red', 'Red', 'Man of the Match', '1st Goal', 'Round', 'PSO', 'Goals in PSO', 'Own goals', 'Own goal Time'], dtype='object')

숫자로 되어 있는 컬럼의 평균/중간값등의 값 구하려면 .describe()

data.describe()
20190723142658.png


특정 열을 가져오려면 data['컬럼']

data['Team'].head()
0 Russia
1 Saudi Arabia
2 Egypt
3 Uruguay
4 Morocco
Name: Team, dtype: object


두개 이상의 열을 가져오려면 data[['컬럼1','컬럼2']]

data[['Team','Goal Scored']].tail()
Team Goal Scored
123 England 1
124 Belgium 2
125 England 0
126 France 4
127 Croatia 2


특정 행을 가져오려면 data.loc[회차]

data.loc[127]
Date 2018-07-15 00:00:00
Team Croatia
Opponent France
Goal Scored 2
Ball Possession % 61
Attempts 15
On-Target 3
Off-Target 8
Blocked 4
Corners 6
Offsides 1
Free Kicks 15
Saves 3
Pass Accuracy % 83
Passes 547
Distance Covered (Kms) 100
Fouls Committed 13
Yellow Card 1
Yellow & Red 0
Red 0
Man of the Match No
1st Goal 28
Round Final
PSO No
Goals in PSO 0
Own goals NaN
Own goal Time NaN
Host Country Russia
Ball Control Good
Name: 127, dtype: object

두개 이상의 행을 가져오려면 .loc[[인덱스1,인덱스2]] 혹은 .loc[[슬라이싱]]

data.loc[[0,127]]
20190723143704.png


특정 행과 열 모두 가져오려면 .loc[[인덱스],[컬럼]]

data.loc[[0,127],['Team',"Goal Scored"]]
Team Goal Scored
0 Russia 5
127 Croatia 2


조건에 맞는 열 값만 보려면 .loc[data['컬럼'] 조건,['컬럼1','컬럼2']]

data.loc[data["Team"] == "France",["Goal Scored","Round"]]
20190723144653.png


컬럼을 삭제 하라면 .drop(['컬럼1','컬럼2'], axis=1)

data2 = data.drop(['Fouls Committed', 'Yellow & Red', 'Man of the Match', '1st Goal', 'PSO','Goals in PSO', 'Own goals', 'Own goal Time'], axis=1)
20190723143849.png


색인 data[data[컬럼] 조건] 혹은 data[data.컬럼 조건] 혹은 data[data[컬럼].isin([조건])]

data2[data2["Team"] == "France"]
data2[data2.Team == 'France']
data2[data2['Team'].isin(['France'])]
20190723145442.png


한번에 여러번 색인 data[data['컬럼'].isin(['조건1', '조건2'])]

data2[data2['Team'].isin(["France","Korea Republic"])]

위에 내용을 풀어서 쓰면
FR_KR = ["France","Korea Republic"]
Team_FR_KR = data2["Team"].isin(FR_KR)
data2[Team_FR_KR]
20190723150640.png

특정 단어가 포함되어 있는 열을 색인 data['컬럼'].srt.contains('단어')

data_KR = data['Team'].str.contains("Korea")
data[data_KR]
20190723150717.png

여러 조건을 동시에 색인 data[(data['컬럼'] 조건) & (data['컬럼'] 조건)]

data[(data['Goal Scored'] > 3) & (data['Yellow Card'] == 0) ]

위에 내용을 풀어서 쓰면
Goal_3over = data['Goal Scored'] > 3
YC_0 = data['Yellow Card'] == 0
data[Goal_3over & YC_0]
20190723150742.png


날짜 데이터를 연월일로 구분하려면 to_datetime(data[날짜 컬럼])

data2['Date'] = pd.to_datetime(data2['Date'])
data2['Date'].dt.year.head()
0 2018
1 2018
2 2018
3 2018
4 2018
Name: Date, dtype: int64


피벗 테이블은 pd.pivot_table(data, index='컬럼', values='컬럼')

pd.pivot_table(data2, index='Round', values='Goal Scored')
20190723151211.png

다양한 조건의 피벗 테이블은 pd.pivot_table(data, index=['컬럼1','컬럼2'], values=['컬럼3','컬럼4'])

pd.pivot_table(data2, index=['Team','Round'], values=['Goal Scored','Yellow Card','Red'])


피벗테이블에 더하기를 추가하려면 numpy를 추가

pd.pivot_table(data, index='Round', values=['Goal Scored','Yellow Card','Red'], aggfunc=np.sum)


동일한 값의 새로운 컬럼을 추가하려면 data['새로운 컬럼'] = '값'

data['Host Country'] = "Russia"
data['Host Country'].head()
0 Russia
1 Russia
2 Russia
3 Russia
4 Russia
Name: Host Country, dtype: object

조건에 맞는 값을 새로운 컬럼에 추가하려면 data.loc[data['컬럼']조건, '새로운 컬럼'] = '값'

data2.loc[data2['Ball Possession %'] > 70 , "Ball Control"] = "Perfect"
data2.loc[(data2['Ball Possession %'] <= 70) & (data2['Ball Possession %'] > 50) , "Ball Control"] = "Good"
data2.loc[(data2['Ball Possession %'] <= 50) & (data2['Ball Possession %'] > 30) , "Ball Control"] = "Bad"
data2.loc[data2['Ball Possession %'] <= 30 , "Ball Control"] = "Worst"
data2[['Ball Possession %','Ball Control']].head(12)
20190723152538.png


keyword
작가의 이전글[Python]기본을 배우는 Kee