2013-08-20 174 views
1

我有这样的数据帧大熊猫GROUPBY值在不同的列

frame = pd.DataFrame({'player1' : ['Joe', 'Steve', 'Bill', 'Doug', 'Steve','Bill','Joe','Steve'], 
         'player2' : ['Bill', 'Doug', 'Steve', 'Joe', 'Bill', 'Steve', 'Doug', 'Bill'], 
         'winner' : ['Joe','Steve' , 'Steve','Doug', 'Bill', 'Steve', 'Doug', 'Steve'], 
         'loser' : ['Bill', 'Doug', 'Bill', 'Joe', 'Steve', 'Bill', 'Joe', 'Bill'], 
         'ones' : 1}) 

我可以保持一个运行总计多少次冠军已经这样做赢了。

frame['winners_wins'] = frame.groupby('winner')['ones'].cumsum() 

我想继续计算player1的胜利和失败次数,对于player2也是如此。 我想我应该可以用groupby函数来做到这一点,但我不知道如何编写它。

编辑:

我没有说出来很井的第一次。我想跟踪每个球员。因此,所需的输出将是:

player1 player2 winner loser player1_wins player2_wins 
Joe  Bill  Joe Bill  1    0 
Steve Doug  Steve Doug  1    0 
Bill Steve Steve Bill  0    2 
Doug Joe  Doug Joe  1    1 
Steve Bill  Bill Steve  2    1 
Bill Steve Steve Bill  1    3 
Joe  Doug  Doug Joe  1    2 
Steve Bill  Steve Bill  3    1 

回答

1

它看起来像你想的运行总计player1'splayer2's胜。这是一个相当普通的方式来使用Python,而不是Pandas。

需要按顺序逐行遍历行并使用先前结果计算下一行的计算往往不会有利于熊猫/ Numpy操作 - cumsum是一个例外。 所以我不认为有一种使用Pandas操作的方法,但我可能是错的。

import pandas as pd 
import collections 

df = pd.DataFrame({'player1' : ['Joe', 'Steve', 'Bill', 'Doug', 
         'Steve','Bill','Joe','Steve'], 'player2' : ['Bill', 
         'Doug', 'Steve', 'Joe', 'Bill', 'Steve', 'Doug', 'Bill'], 
         'winner' : ['Joe','Steve' , 'Steve','Doug', 'Bill', 
         'Steve', 'Doug', 'Steve'], 'loser' : ['Bill', 'Doug', 
         'Bill', 'Joe', 'Steve', 'Bill', 'Joe', 'Bill'], }, 
        columns = ['player1', 'player2', 'winner', 'loser']) 

wins = collections.Counter() 
def count_wins(): 
    for idx, row in df.iterrows(): 
     wins[row['winner']] += 1 
     yield wins[row['player1']], wins[row['player2']] 
df['player1_wins'], df['player2_wins'] = zip(*list(count_wins())) 
print(df) 

打印

player1 player2 winner loser player1_wins player2_wins 
0  Joe Bill Joe Bill    1    0 
1 Steve Doug Steve Doug    1    0 
2 Bill Steve Steve Bill    0    2 
3 Doug  Joe Doug Joe    1    1 
4 Steve Bill Bill Steve    2    1 
5 Bill Steve Steve Bill    1    3 
6  Joe Doug Doug Joe    1    2 
7 Steve Bill Steve Bill    4    1 
1

没有必要的 “个位” 栏,或者说真的,进行分组。获得winners_wins无需采取 “一” 列

In [19]: del frame['ones'] 

In [20]: frame['player1_wins'] = (frame['winner'] == frame['player1']).astype('int').cumsum() 

In [21]: frame['player2_wins'] = (frame['winner'] == frame['player2']).astype('int').cumsum() 

In [22]: frame 
Out[22]: 
    loser player1 player2 winner player1_wins player2_wins 
0 Bill  Joe Bill Joe    1    0 
1 Doug Steve Doug Steve    2    0 
2 Bill Bill Steve Steve    2    1 
3 Joe Doug  Joe Doug    3    1 
4 Steve Steve Bill Bill    3    2 
5 Bill Bill Steve Steve    3    3 
6 Joe  Joe Doug Doug    3    4 
7 Bill Steve Bill Steve    4    4 

一种方法是这样的:

In [26]: frame['winners_wins'] = frame.groupby('winner').winner.transform(lambda x: np.arange(1, 1 + len(x))