pandas DataFrame 반복 소개

효율적인 Python 코드 작성

Logan Thomas

Scientific Software Technical Trainer, Enthought

pandas 복습

  • Intermediate Python의 pandas 개요 참고
  • 데이터 분석용 라이브러리
  • 주요 자료 구조: DataFrame
    • 행/열 라벨이 있는 표 형식 데이터
    • NumPy 배열 구조 위에 구축
  • 이번 장 목표:
    • pandas DataFrame 반복의 모범 사례
효율적인 Python 코드 작성

야구 통계

import pandas as pd

baseball_df = pd.read_csv('baseball_stats.csv')
print(baseball_df.head())
  Team League  Year   RS   RA   W    G  Playoffs
0  ARI     NL  2012  734  688  81  162         0
1  ATL     NL  2012  700  600  94  162         1
2  BAL     AL  2012  712  705  93  162         1
3  BOS     AL  2012  734  806  69  162         0
4  CHC     NL  2012  613  759  61  162         0
효율적인 Python 코드 작성

야구 통계

  Team
0  ARI     
1  ATL     
2  BAL     
3  BOS     
4  CHC

alt=”아리조나 다이아몬드백스 로고와 아래 ARI 텍스트, 애틀랜타 브레이브스 로고와 아래 ATL 텍스트, 볼티모어 오리올스 로고와 아래 BAL 텍스트, 보스턴 레드삭스 로고와 아래 BOS 텍스트, 시카고 컵스 로고와 아래 CHC 텍스트”

효율적인 Python 코드 작성

야구 통계

  Team League  Year   RS   RA   W    G  Playoffs
0  ARI     NL  2012  734  688  81  162         0
1  ATL     NL  2012  700  600  94  162         1
2  BAL     AL  2012  712  705  93  162         1
3  BOS     AL  2012  734  806  69  162         0
4  CHC     NL  2012  613  759  61  162         0
효율적인 Python 코드 작성

승률 계산하기

import numpy as np

def calc_win_perc(wins, games_played):

    win_perc = wins / games_played

    return np.round(win_perc,2)
win_perc = calc_win_perc(50, 100)
print(win_perc)
0.5
효율적인 Python 코드 작성

DataFrame에 승률 추가하기

win_perc_list = []

for i in range(len(baseball_df)): row = baseball_df.iloc[i]
wins = row['W'] games_played = row['G']
win_perc = calc_win_perc(wins, games_played)
win_perc_list.append(win_perc)
baseball_df['WP'] = win_perc_list
효율적인 Python 코드 작성

DataFrame에 승률 추가하기

print(baseball_df.head())
  Team League  Year   RS   RA   W    G  Playoffs    WP
0  ARI     NL  2012  734  688  81  162         0  0.50
1  ATL     NL  2012  700  600  94  162         1  0.58
2  BAL     AL  2012  712  705  93  162         1  0.57
3  BOS     AL  2012  734  806  69  162         0  0.43
4  CHC     NL  2012  613  759  61  162         0  0.38
효율적인 Python 코드 작성

.iloc으로 반복하기

%%timeit
win_perc_list = []

for i in range(len(baseball_df)):
    row = baseball_df.iloc[i]

    wins = row['W']
    games_played = row['G']

    win_perc = calc_win_perc(wins, games_played)
    win_perc_list.append(win_perc)

baseball_df['WP'] = win_perc_list
183 ms ± 1.73 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
효율적인 Python 코드 작성

.iterrows()로 반복하기

win_perc_list = []

for i,row in baseball_df.iterrows():

wins = row['W'] games_played = row['G'] win_perc = calc_win_perc(wins, games_played) win_perc_list.append(win_perc) baseball_df['WP'] = win_perc_list
효율적인 Python 코드 작성

.iterrows()로 반복하기

%%timeit
win_perc_list = []

for i,row in baseball_df.iterrows():

    wins = row['W']
    games_played = row['G']

    win_perc = calc_win_perc(wins, games_played)
    win_perc_list.append(win_perc)

baseball_df['WP'] = win_perc_list
95.3 ms ± 3.57 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
효율적인 Python 코드 작성

.iterrows()로 DataFrame 반복 연습

효율적인 Python 코드 작성

Preparing Video For Download...