本文介绍了使用 groupby 和 loc 设置新的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框如下:

df = pd.DataFrame()
df['Team1']   = ['A','B','C','D','E','F','A','B','C','D','E','F']
df['Score1']  = [1,2,3,1,2,4,1,2,3,1,2,4]
df['Team2']   = ['U','V','W','X','Y','Z','U','V','W','X','Y','Z']
df['Score2']  = [2,1,2,2,3,3,2,1,2,2,3,3]
df['Match']   = df['Team1']  + ' Vs '+ df['Team2']
df['Match_no']= [1,2,3,4,5,6,1,2,3,4,5,6]
df['model']  = ['ELO','ELO','ELO','ELO','ELO','ELO','xG','xG','xG','xG','xG','xG']
winner = df.Score1>df.Score2
df['winner']  = np.where(winner,df['Team1'],df['Team2'])

我想做的是为下一阶段的锦标赛创建另一个日期框架.在下一阶段,我们将为每个模型(ELO 和 xG)提供 3 个匹配项.我想按 模型 分组.这些比赛按型号分组,第 1 场比赛和第 1 场比赛的获胜者、第 3 场比赛的获胜者对第 4 场比赛的获胜者等将进行(即 U 对 B、C 对 X、Y 对 F).那么谁能告诉我如何提取这些团队?

What I want to do is to create another date frame for next stage of tournament. In next stage , we will have 3 matches for each Model (ELO and xG).I would like to groupby Model. These matches are groupped by Model, winner from match number 1 and match number 1,winner from Match number 3 vs match number 4 etc. will play (i.e. U vs B,C vs X, Y vs F). Then Can anyone advise me how to extract those teams?

我预期的新数据框如下:

my expected new dataframe will be as follow:

df1 =pd.DataFrame()
df1['Team1']   = ['U','C','Y','U','C','Y']
df1['Team2']   = ['B','X','F','B','X','F']

df1['Match']   = df1['Team1']  + ' Vs '+ df1['Team2']
df1['Match_no']= [1,2,3,1,2,3]
df1['model']  = ['ELO','ELO','ELO','xG','xG','xG']

我该如何设置?谢谢,

Zep

推荐答案

您可以使用 GroupBy.cumcount 用于每组计数:

You can use GroupBy.cumcount for count per groups:

df1 = pd.DataFrame()
df1['Team1'] = df.loc[::2, 'winner'].values
df1['Team2'] = df.loc[1::2, 'winner'].values
df1['Match'] = df1['Team1']  + ' Vs '+ df1['Team2']
model = df.loc[::2, 'model'].values
df1['Match_no'] = df1.groupby(model).cumcount() + 1
df1['model'] = model
print (df1)
  Team1 Team2   Match  Match_no model
0     U     B  U Vs B         1   ELO
1     C     X  C Vs X         2   ELO
2     Y     F  Y Vs F         3   ELO
3     U     B  U Vs B         1    xG
4     C     X  C Vs X         2    xG
5     Y     F  Y Vs F         3    xG

这篇关于使用 groupby 和 loc 设置新的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:54