Adding win percentage to a Pandas DataFrame involves calculating the win percentage for each row and then adding a new column to the DataFrame to store the results. Here's an example:
import pandas as pd# Create example DataFramedf = pd.DataFrame({'Team': ['A', 'B', 'C'], 'Wins': [20, 15, 10], 'Games Played': [30, 30, 30]})# Calculate win percentage for each rowdf['Win Percentage'] = df['Wins'] / df['Games Played']# 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 create an example DataFrame with columns for Team, Wins, and Games Played. We then calculate the win percentage for each row by dividing the Wins column by the Games Played column, and assign the results to a new column called Win Percentage. Finally, we print the results to the console.
Note that the column order is preserved in the new DataFrame, so the Win Percentage column is added as the last column. If you want to reorder the columns, you can use the reindex() method or simply select the columns in the order you want them.