我有一个名为‘df’的Pandas 数据帧,它有29列.我正在使用的数据帧的一个例子是,用更好的方式显示它的列更少:
tourney_name | draw_size | player1_id | player1_age | player2_id | player2_age |
---|---|---|---|---|---|
A | 32 | 10001 | 23 | 10002 | 18 |
A | 32 | 10003 | 24 | 10004 | 30 |
A | 32 | 10005 | 25 | 10006 | 28 |
B | 64 | 10003 | 24 | 10002 | 18 |
B | 64 | 10006 | 28 | 10001 | 23 |
现在的DF是,Player1列中的所有球员都是赢得比赛的球员,而Player2列中的球员是输掉这场比赛的球员.
我需要一个结果df,它在一些行中随机洗牌一些球员数据,这样我就可以添加一个‘Target’变量,如果player1列中的球员是赢得比赛的那个人,则显示‘1’,如果player1列中的球员输掉了比赛,则显示‘0’. 生成的df应该如下所示:
tourney_name | draw_size | player1_id | player1_age | player2_id | player2_age | target |
---|---|---|---|---|---|---|
A | 32 | 10001 | 23 | 10002 | 18 | 1 |
A | 32 | 10004 | 30 | 10003 | 24 | 0 |
A | 32 | 10006 | 28 | 10005 | 25 | 0 |
B | 64 | 10003 | 24 | 10002 | 18 | 1 |
B | 64 | 10001 | 23 | 10006 | 28 | 0 |
为了完成我需要的工作,我创建了以下代码:
# Create a new DataFrame for modeling
model_df = pd.DataFrame()
# Iterate through each row
for index, row in df.iterrows():
# Randomly assign the winner and loser information to Player1 and Player2
common_cols = ['tourney_name', 'draw_size', 'tourney_level', 'tourney_date', 'best_of', 'round', 'minutes', 'surface_Carpet', 'surface_Clay', 'surface_Grass', 'surface_Hard']
common_data = row[common_cols]
winner_cols = ['player1_id', 'player1_seed', 'player1_entry', 'player1_hand', 'player1_ht', 'player1_ioc', 'player1_age', 'player1_rank', 'player1_rank_points']
loser_cols = ['player2_id', 'player2_seed', 'player2_entry', 'player2_hand', 'player2_ht', 'player2_ioc', 'player2_age', 'player2_rank', 'player2_rank_points']
# Randomly choose winner and loser columns
if np.random.rand() < 0.5:
winner_data = row[winner_cols]
loser_data = row[loser_cols]
target = 1 # Player1 is the winner
else:
winner_data = row[loser_cols]
loser_data = row[winner_cols]
target = 0 # Player1 is the loser
combined_data = pd.concat([common_data, winner_data, loser_data, pd.Series([target], name='target')], axis=0)
model_df = pd.concat([model_df, combined_data], axis=1)
model_df = model_df.transpose()
# Renaming the column '0' to 'target'
model_df.rename(columns={0: 'target'}, inplace=True)
# Reset the index of the resulting DataFrame
model_df.reset_index(drop=True, inplace=True)
使用这段代码,我希望得到所需的数据帧,但它所做的唯一事情就是将player1和player2列中的所有数据保留在同一位置,或者将所有player1列中的数据切换到player2列,并将player2数据切换到player1列.它要么切换所有线路,要么不切换,当我需要切换一些线路和不切换一些线路时.生成的数据帧如下所示:
tourney_name | draw_size | player2_id | player2_age | player1_id | player1_age | target |
---|---|---|---|---|---|---|
A | 32 | 10002 | 18 | 10001 | 23 | 1 |
A | 32 | 10004 | 30 | 10003 | 24 | 0 |
A | 32 | 10006 | 28 | 10005 | 25 | 0 |
B | 64 | 10002 | 18 | 10003 | 24 | 1 |
B | 64 | 10001 | 23 | 10006 | 28 | 0 |