【问题标题】:Pandas Dataframe, aggregate and put the data in the next columnPandas Dataframe,聚合并将数据放在下一列
【发布时间】:2017-01-04 14:47:48
【问题描述】:

我有一个这样的数据集:

Country   Name      Match   Result
US        Martin    Win     3
US        Martin    Lose    1
US        Martin    Draw    5
UK        Luther    Win     5
UK        Luther    Draw    3

我想再添加两列,其中包含获胜、失败和平局的总和结果,以及每场比赛的百分比,如下所示:

Country   Name      Match   Result  All Percentage
US        Martin    Win     3       8   0.375
US        Martin    Lose    1       8   0.125
US        Martin    Draw    5       8   0.625
UK        Luther    Win     6       10  0.6
UK        Luther    Draw    4       10  0.4

我已经尝试过使用 groupby 并得到了大小总匹配的结果。但是我不知道如何将它放在下一个专栏中。

谢谢

【问题讨论】:

  • MartinAll 列不应该是 9,而不是 8 (5 + 3 + 1)?
  • 是的,我的错,应该是 (5+1+2) .. 谢谢

标签: python pandas aggregate data-science


【解决方案1】:

您需要的IIUC GroupBy.transform,示例DataFrame 已更改:

df['All'] = df.groupby(['Country','Name'])['Result'].transform('sum')
df['Percentage'] = df.Result.div(df.All)
print (df)
  Country    Name Match  Result  All  Percentage
0      US  Martin   Win       2    8       0.250
1      US  Martin  Lose       1    8       0.125
2      US  Martin  Draw       5    8       0.625
3      UK  Luther   Win       6   10       0.600
4      UK  Luther  Draw       4   10       0.400

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-21
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 2020-03-06
    相关资源
    最近更新 更多