【发布时间】:2015-09-04 08:26:11
【问题描述】:
我有一个熊猫数据框matches,其中包含如下匹配结果:
year winner loser score
1990 A B 6-0
1990 B C 5-0 RET
1990 A B 4-0 RET
1990 C C 6-0
1991 A B 6-1
1991 A C 4-1 RET
1991 B A 6-4
1991 C A 3-0 RET
我想创建一个新的数据框,其中包含每位玩家每年的 wins、losses 和 退休后获胜。 最终输出应如下所示:
year player wins losses rets
1990 A 2 0 1
1990 B 1 2 1
1990 C 1 2 0
1991 A 2 2 1
1991 B 1 1 0
1991 C 1 1 1
对于输赢,我可以成功地做到这一点。 我愿意:
w_group = matches.groupby(['year', 'winner']).size()
l_group = matches.groupby(['year', 'loser']).size()
然后创建一个新的数据框:
scores = pd.DataFrame({'wins' : w_group, 'losses' : l_group}).fillna(0)
#name the index
scores.index.names = ['year','player']
但是,对于通过退休计算胜利,我不知道如何实现该列。我试过这个:
ret_group = matches.groupby(['year', 'winner']).apply(lambda x: x[(x['score'].str.contains('RET').fillna(False))].count())
但这给了我以下例外:
raise KeyError('%s not in index' % objarr[mask])
KeyError: '[ 0.] not in index'
非常感谢您的解决方案
【问题讨论】:
-
你的代码对我有用(Python 3.4.3,pandas 0.16.2)。
-
它会产生预期的结果吗?也就是说,一个新的数据框,其中包含 wins/losses/rets 列?
-
我得到一个包含以下列的数据框:
'year', 'winner', 'loser', 'score','score'包含您要查找的结果 ([1, 1, 0, 1, 0, 1])。 -
嗯。我想达到这个。阅读上面的“最终输出应该看起来像:”这就是我需要的。
-
但是你所要做的就是
scores['rets'] = ret_group['score']。你最大的问题是你得到的错误,我无法重现,对吧?
标签: python pandas group-by dataframe