The .iloc method in Pandas can be used to iterate through a DataFrame row by row. Here's an example of how to use .iloc 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 .ilocfor 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 .iloc, 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 while .iloc can be used to iterate through a DataFrame row by row, it can be slower than vectorized operations like the method described in my previous answer. If possible, it's generally better to avoid using loops and use vectorized operations instead. However, if you need to perform complex calculations that can't be done with vectorized operations, .iloc can be a useful tool.