gpt4 book ai didi

Python数据框获取特定行占总行的比率

转载 作者:行者123 更新时间:2023-12-01 08:01:13 27 4
gpt4 key购买 nike

一个简单的数据框。我想要显示“已测试”列中 22 行数占总行数的百分比。

即1.“已测试”列中有 5 行,每行 22 个

  • 数据框共15行
  • 所以百分比是 5/15 = 0.33

    我在下面尝试过,但它给出零。

    我该如何纠正它?谢谢。

    import pandas as pd

    data = {'Unit_Weight': [335,335,119,119,52,452,19,19,19,165,165,165,724,724,16],
    'Tested' : [22,12,14,16,18,20,22,24,26,28,22,22,48,50,22]}

    df = pd.DataFrame(data)

    num_row = df.shape[0]

    suspect_row = df[df["Tested"] == 22].shape[0]

    suspect_over_total = suspect_row/num_row

    print num_row # 15
    print suspect_row # 5

    print float(suspect_over_total) # 0.0

    最佳答案

    suspect_over_total = Suspect_row/num_row 表示您正在执行 int/int 运算,其结果为 0.3333333,因此Python 将为您提供 int 结果,在本例中为 0

    正如 bubble 所说,您应该将其中一个操作数转换为 float:

    suspect_over_total = float(suspect_row)/num_row   # 0.33333333333

    关于Python数据框获取特定行占总行的比率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55719238/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com