My data frame df
is comprised of pairs of rows with matching index columns ['game_id']
and differing values otherwise. If I want to create a column that references a value from the other row of that same index, how do I do that?
For example, if I'm in the first row of ['game_id']
and I want to create a column for ['FGA']
values of the pair's match, how do I do that? The first row would return 85
while the second would return 90
. In the ['game_id'] == 21900017 rows
, the first row would return 78
while the second row would return 109
.
game_id Team PTS FGM Miss FTA TOV Foul ORB DRB UA FGA FG% A%
21900008 BOS 93 33 57 34 10 29 10 31 15 90 0.367 0.545
21900008 PHI 107 37 48 36 15 34 12 50 13 85 0.435 0.649
21900017 BOS 112 42 67 16 9 21 21 35 21 109 0.385 0.5
21900017 TOR 106 37 41 17 23 28 5 41 15 78 0.474 0.595
You can use groupby()
and apply()
and reverse the index of the grouped series to find the value of the pair:
df['FGA_pair'] = df.groupby('game_id')['FGA'].apply(lambda x: x.iloc[::-1]).reset_index(drop=True)
Yields:
game_id Team PTS FGM Miss FTA ... DRB UA FGA FG% A% FGA_pair
0 21900008 BOS 93 33 57 34 ... 31 15 90 0.367 0.545 85
1 21900008 PHI 107 37 48 36 ... 50 13 85 0.435 0.649 90
2 21900017 BOS 112 42 67 16 ... 35 21 109 0.385 0.500 78
3 21900017 TOR 106 37 41 17 ... 41 15 78 0.474 0.595 109
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.