I'm looking for a way to convert 5 rows in a pandas dataframe into one row with 5 times the amount of columns (so I have the same information, just squashed into one row). Let me explain:
I'm working with hockey game statistics. Currently, there are 5 rows representing the same game in different situations
, each with 111 columns. I want to convert these 5 rows into one row (so that one game is represented by one row) but keep the information contained in the different situations. In other words, I want to convert 5 rows, each with 111 columns into one row with 554 columns (554=111*5 minus one since we're joining on gameId
).
So, as an example, we can see the first 5 rows have gameId = 2008020001
, but each have a different situation
(i.e. other
, all
, 5on5
, 4on5
, and 5on4
). I'd like these 5 rows to be converted into one row with gameId = 2008020001
, and with columns labelled according to their situation.
For example, I want columns for all unblockedShotAttemptsAgainst
, 5on5 unblockedShotAttemptsAgainst
, 5on4 unblockedShotAttemptsAgainst
, 4on5 unblockedShotAttemptsAgainst
, and other unblockedShotAttemptsAgainst
(and the same for every other stat).
Any info would be greatly appreciated. It's also worth mentioning that my dataset is fairly large (177990 rows), so an efficient solution is desired. The resulting dataframe should have one-fifth the rows and 5 times the columns. Thanks in advance!
---- What I've Tried Already ----
I tried to do this using df.apply()
and some nested for
loops, but it got very ugly very quickly and was incredibly slow. I think pandas has a better way of doing this, but I'm not sure how.
Looking at other SO answers, I initially thought it might have something to do with df.pivot()
or df.groupby()
, but I couldn't figure it out. Thanks again!
source https://stackoverflow.com/questions/74565718/pandas-how-to-squash-multiple-rows-into-one-row-with-more-columns
Comments
Post a Comment