Printing All Rows In Each Level Of Multiindex Pd.dataframe In One Row
I have a dataframe which was converted into a multiIndex dataframe after doing groupby() and aggregation. In[1]: mydata = [['Team1', 'Player1', 'idTrip13', 133], ['Team2', 'Player
Solution 1:
Iterate through the 0th level (team) using
groupby()
.forteam, df2 in player_total.groupby(level = 0):
For example at the second iteration, it will return a dataframe for
Team2
:trips time team player Team2 Player293 117656 Player333 118373
Use
reset_index()
to drop the team index column and make the player index column as part of the dataframe.>>>team_df = df2.reset_index(level =0, drop=True).reset_index() >>>team_df player trips time0 Player293 1176561 Player333 118373
Convert that dataframe into a list of lists so we can iterate through each player.
team_df.values.tolist() >>>[['Player293', 1, 17656], ['Player333', 1, 18373]]
When printing we have to map the integers to a string, and use the end parameter of the print function to print a semicolon instead of printing a new line at the end.
>>>for player in team_df.values.tolist(): print(': '.join(map(str, player)), end = '; ') >>>Player293: 1: 17656; Player333: 1: 18373;
The full solution:
from __future__ import print_function
#iterate through each teamfor team, df2 in player_total.groupby(level = 0):
print(team, end = '\t')
#drop the 0th level (team) and move the first level (player) as the index
team_df = df2.reset_index(level = 0, drop = True).reset_index()
#iterate through each player on the team and print player, trip, and timefor player in team_df.values.tolist():
print(': '.join(map(str, player)), end = '; ')
#After printing all players insert a new lineprint()
Output:
Player1: 2:19526;Player293: 1:17656;Player333: 1:18373;Player20: 1:1883;Player22: 1:17338899;
Post a Comment for "Printing All Rows In Each Level Of Multiindex Pd.dataframe In One Row"