.itertuples() is another method in Pandas that can be used to iterate through a DataFrame row by row. It returns an iterator yielding namedtuples of the rows. Here's an example of how to use .itertuples() 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 .itertuples()for row in df.itertuples(): # Calculate win percentage for current row win_pct = row.Wins / row._2 # Add win percentage to DataFrame df.at[row.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 .itertuples(), 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 .itertuples() can be faster than .iterrows() and .iloc, as it doesn't convert each row to a Series object. However, it returns namedtuples, which can be less convenient to work with than Series or DataFrame objects.