I have a csv file containing games and stats for each team for an entire season. I am wanting to move the away team into the same row as the home team it faced for that week.
Current dataframe:
Week Team H/a Opp Pf Pa Pyards
1 A C 3 14 100
1 B D 7 21 200
1 C @ A 14 3 300
1 D @ B 21 7 400
Desired dataframe:
Week HomeTeam H-score H-Pyards AwayTeam A-score A-Pyards
1 A 3 100 C 14 300
1 B 7 200 D 21 400
But I would have more stats for each team and mutliple weeks.
I believe the operation you are looking is self-join
with some manipulation afterwards. As Quang Hoang stated, merging the same dataframe/table in different columns is called self-join. I believe this is an approach which gets the expected output:
df = pd.DataFrame({'Week':[1,1,1,1],
'Team':['A','B','C','D'],
'H/a':[np.nan,np.nan,'@','@'],
'Opp':['C','D','A','B'],
'Pf':[3,7,14,21],
'Pa':[14,21,3,7],
'Pyards':[100,200,300,400]})
print(df)
new_df = df.merge(df,how='inner',left_on=['Week','Team'],right_on=['Week','Opp'])
new_df = new_df[new_df['H/a_x'] != '@']
replacers = {'Team_x':'HomeTeam','Pf_x':'Pf','Pyards_x':'H-Pyards','Opp_x':'AwayTeam','Pa_x':'A-score','Pyards_y':'A-Pyards'}
new_df = new_df[['Week']+[x for x in replacers.keys()]]
new_df = new_df.rename(columns=replacers)
print(new_df)
Output:
Week HomeTeam Pf H-Pyards AwayTeam A-score A-Pyards
0 1 A 3 100 C 14 300
1 1 B 7 200 D 21 400
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.