Introdução à iteração em DataFrames do pandas

Escrevendo código Python eficiente

Logan Thomas

Scientific Software Technical Trainer, Enthought

Revisão do pandas

  • Veja a visão geral do pandas em Intermediate Python
  • Biblioteca para análise de dados
  • Principal estrutura: DataFrame
    • Dados tabulares com linhas e colunas rotuladas
    • Baseado na estrutura de arrays do NumPy
  • Objetivo do capítulo:
    • Boas práticas para iterar em um DataFrame do pandas
Escrevendo código Python eficiente

Estatísticas de beisebol

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
Escrevendo código Python eficiente

Estatísticas de beisebol

  Team
0  ARI     
1  ATL     
2  BAL     
3  BOS     
4  CHC

alt=”Logotipo do Arizona Diamondbacks com o texto ARI abaixo, logotipo do Atlanta Braves com o texto ATL abaixo, logotipo do Baltimore Orioles com o texto BAL abaixo, logotipo do Boston Red Sox com BOS abaixo e logotipo do Chicago Cubs com CHC abaixo”

Escrevendo código Python eficiente

Estatísticas de beisebol

  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
Escrevendo código Python eficiente

Calculando % de vitórias

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
Escrevendo código Python eficiente

Adicionando % de vitórias ao 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
Escrevendo código Python eficiente

Adicionando % de vitórias ao 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
Escrevendo código Python eficiente

Iterando com .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 por loop (média ± desvio padrão de 7 execuções, 10 loops cada)
Escrevendo código Python eficiente

Iterando com .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
Escrevendo código Python eficiente

Iterando com .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 por loop (média ± desvio padrão de 7 execuções, 10 loops cada)
Escrevendo código Python eficiente

Pratique iterar em DataFrame com .iterrows()

Escrevendo código Python eficiente

Preparing Video For Download...