在一行

时间:2015-12-31 01:41:36

标签: python pandas aggregate

我有一个数据框,在执行groupby()aggregation后转换为multiIndex数据框。

In[1]:

mydata = [['Team1', 'Player1', 'idTrip13', 133], ['Team2', 'Player333', 'idTrip10', 18373],
['Team3', 'Player22', 'idTrip12', 17338899], ['Team2', 'Player293','idTrip02', 17656], 
['Team3', 'Player20', 'idTrip11', 1883], ['Team1', 'Player1', 'idTrip19', 19393]]

df = pd.DataFrame(mydata, columns = ['team', 'player', 'trips', 'time'])
df
Out[1]:
     team    player       trips      time
0   Team1   Player1     idTrip13    133
1   Team2   Player333   idTrip10    18373
2   Team3   Player22    idTrip12    17338899
3   Team2   Player293   idTrip02    17656
4   Team3   Player20    idTrip11    1883
5   Team1   Player1     idTrip19    19393

对于团队中的每位玩家,查找旅行总次数和旅行总时间。这将返回一个multiIndex数据帧。

player_total = df.groupby(by = ['team', 'player']).agg({'time' : 'sum', 'trips' : 'count'})

player_total
Out[4]:
                 trips  time
team    player      
Team1   Player1     2   19526
Team2   Player293   1   17656
        Player333   1   18373
Team3   Player20    1   1883
        Player22    1   17338899

期望的输出: 我想打印输出,以便团队中的所有玩家都在同一条线上。

Team1   Player1 : 2 trips : 19526;
Team2   Player293 : 1 : 17656; Player333 : 1 : 18373;
Team3   Player22 : 1 trip : 17338899; Player20 : 1 trip : 1883

question被认为过于宽泛,因此我冒昧地将pandas数据帧创建/聚合从输出打印中分离出来。

1 个答案:

答案 0 :(得分:0)

  1. 使用groupby()遍历第0级(团队)。

    for team, df2 in player_total.groupby(level = 0):
    

    例如,在第二次迭代中,它将返回Team2的数据帧:

                    trips   time
    team  player              
    Team2 Player293     1  17656
          Player333     1  18373
    
  2. 使用reset_index()删除团队索引列,并将播放器索引列作为数据帧的一部分。

    >>>team_df = df2.reset_index(level = 0, drop = True).reset_index()
    >>>team_df
          player  trips   time
    0  Player293     1  17656
    1  Player333     1  18373
    
  3. 将该数据帧转换为列表列表,以便我们可以遍历每个播放器。

    team_df.values.tolist()
    >>>[['Player293', 1, 17656], ['Player333', 1, 18373]]
    
  4. 打印时我们必须将整数映射到字符串,然后使用print函数的end参数打印分号,而不是在末尾打印新行。

    >>>for player in team_df.values.tolist():
           print(': '.join(map(str, player)), end = '; ')
    >>>Player293: 1: 17656; Player333: 1: 18373; 
    
  5. 完整的解决方案:

    from __future__ import print_function
    
    #iterate through each team
    for 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 time
        for player in team_df.values.tolist():
            print(': '.join(map(str, player)), end = '; ')
        #After printing all players insert a new line
        print()
    

    <强>输出:

    Player1: 2: 19526; 
    Player293: 1: 17656; Player333: 1: 18373; 
    Player20: 1: 1883; Player22: 1: 17338899;