The .iterrows() method in Pandas can also be used to iterate through a DataFrame row by row. Here's an example of how to use .iterrows() to calculate the win percentage for each row:
import pandas as pd# Create example DataFramedf = pd.DataFrame({'Team': ['A', 'B', 'C'], 'Wins': [20, 15, 10], 'Games Played': [30, 30, 30]})# Iterate through each row using .iterrows()for index, row in df.iterrows(): # Calculate win percentage for current row win_pct = row['Wins'] / row['Games Played'] # Add win percentage to DataFrame df.at[index, 'Win Percentage'] = win_pct# Print the resultsprint(df) |
Output:
Team Wins Games Played Win Percentage0 A 20 30 0.6666671 B 15 30 0.5000002 C 10 30 0.333333 |
In this example, we first create an example DataFrame with columns for Team, Wins, and Games Played. We then use a for loop to iterate through each row using .iterrows(), and calculate the win percentage for the current row by dividing the Wins column by the Games Played column. We use the .at method to add the win percentage to the DataFrame at the current index. Finally, we print the results to the console.
Note that, similar to .iloc, .iterrows() can be slower than vectorized operations like the method described in my previous answer. It's generally recommended to avoid using loops and use vectorized operations instead, but .iterrows() can be a useful tool for certain situations where a loop is necessary.