【问题标题】:adding values from two columns tied to two other columns (where values repeat) in python在python中将两列中的值与其他两列(值重复)相加
【发布时间】:2020-09-18 23:19:04
【问题描述】:

我正在尝试找出 df 中的最佳球队得分手。

但是,如何在“home_team”和“away_team”列中为具有相同名称的团队添加“home_score”和“away_score”列的值。注意:团队名称在两个团队列的行中重复。我看过字典、连接、求和……现在我很困惑。

home_team away_team home_score away_score

  A            D            3          5
  B            C            1          0
  C            B            2          1
  D            A            3          5
  A            B            3          5

在上面的示例中,输出应该是团队 A 和 11 (3+3+5)。我如何在 df 中找到答案?

【问题讨论】:

    标签: python-3.x dataframe data-science


    【解决方案1】:

    获取所有分数数据。

    import collections
    
    score_data = collections.defaultdict(int)
    for _, row in df.iterrows():
        score_data[row[0]] += row[2]
        score_data[row[1]] += row[3]
    

    要获得最高成就者,您可以通过以下技巧找到最高成就。

    top_team, top_score = max((t, s) for s, t in score_data.items())
    

    【讨论】:

    • 谢谢你,凯特-梅尔尼科娃!有效。我要学习更多“收藏”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多