【问题标题】:Pandas groupby - when column is a certain valuePandas groupby - 当列是某个值时
【发布时间】:2020-11-22 14:57:12
【问题描述】:

对于下表:

我想将 groupby 函数与“number_of_horses”一起使用,并在“winner”列中显示“TRUE”值的计数。

使用 Python-Pandas,我已经尝试过:

输入:

df.groupby('number_of_horses').winner.count()

输出:

上面的表格不是我们想要的输出。

想要的输出是:

请注意,“获胜者”列仅在值为 TRUE 时计算在内。

【问题讨论】:

    标签: python pandas sorting group-by count


    【解决方案1】:

    给你:

    df[df.winner == True].groupby('number_of_horses').winner.count().reset_index()                                                                                                                                         
    

    输出

       number_of_horses  winner
    0                 2       2
    1                 3       6
    

    如果winner 列是字符串,则使用df.winner == "TRUE" 作为过滤条件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多