【问题标题】:Counting the number of zero's in a column计算列中零的数量
【发布时间】:2020-08-23 12:48:21
【问题描述】:
df = pd.DataFrame({'Score':[1,2,3,4,5], 'Rate': [1.0, 0.0, 0.0, 0.5, 0.5]})
df.head()  



          Score              Rate
    0       1                1.0
    1       2                0.0
    2       3                0.0
    3       4                0.5
    4       5                0.5

我正在尝试计算 Rates 等于 0 的数量并显示相应的分数

【问题讨论】:

  • 预期输出是什么?

标签: python pandas dataframe data-science counting


【解决方案1】:

你可以使用 loc:

df.loc[df.Rate.eq(0)]

Score   Rate
1   2   0.0
2   3   0.0

或者如果您只需要查看分数:

df.loc[df.Rate.eq(0)].Score

【讨论】:

    【解决方案2】:
    print(df[df['Rate']==0]['Score'])
    

    【讨论】:

      【解决方案3】:

      DataFrame.locboolean indexing 一起使用,然后得到Score 列的计数和总和:

      df = df.loc[df['Rate'].eq(0), 'Score'].agg(['sum','size'])
      print (df)
      sum     5
      size    2
      Name: Score, dtype: int64
      

      【讨论】:

        猜你喜欢
        • 2018-11-06
        • 2019-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多