【问题标题】:How to find count of values within certain range in pandas?如何在熊猫中查找一定范围内的值的计数?
【发布时间】:2019-07-04 13:17:57
【问题描述】:

我有一个包含错误值列表的 pandas 数据框。我想在某些范围内找到我的错误比例,例如我的错误百分比在 +-1%、+-5%、+-10%、+-20% 和 +-50% 等范围内。我的数据直方图如下所示:

到目前为止,我已经查看了诸如 pd.cut() 和 plt.hist() 之类的函数,但似乎没有库可以给出我的范围相互重叠的答案,所以我不得不求助于一个很长的自定义made 函数 - 如下:

def error_distribution(df):

  total_length = len(df.index)
  one_perc = five_perc = ten_perc = fifteen_perc = twenty_perc = thirty_perc \
    = fourty_perc = fifty_perc = over_fifty = 0

  for index, row in df.iterrows():
    value = abs(row['Errors'])

    if value <= 0.01:
      one_perc += 1
      five_perc += 1
      ten_perc += 1
      fifteen_perc += 1
      twenty_perc += 1
      thirty_perc += 1
      fourty_perc += 1
      fifty_perc += 1
    elif value <= 0.05:
      five_perc += 1
      ten_perc += 1
      fifteen_perc += 1
      twenty_perc += 1
      thirty_perc += 1
      fourty_perc += 1
      fifty_perc += 1      
    elif value <= 0.1:
      ten_perc += 1
      fifteen_perc += 1
      twenty_perc += 1
      thirty_perc += 1
      fourty_perc += 1
      fifty_perc += 1
    elif value <= 0.15:
      fifteen_perc += 1
      twenty_perc += 1
      thirty_perc += 1
      fourty_perc += 1
      fifty_perc += 1
    elif value <= 0.2:
      twenty_perc += 1
      thirty_perc += 1
      fourty_perc += 1
      fifty_perc += 1
    elif value <= 0.3:
      thirty_perc += 1
      fourty_perc += 1
      fifty_perc += 1
    elif value <= 0.4:
      fourty_perc += 1
      fifty_perc += 1
    elif value <= 0.5:
      fifty_perc += 1
    else:
      over_fifty += 1

  print("Sub  1%: {0:.2f}%".format(one_perc/total_length*100))
  print("Sub  5%: {0:.2f}%".format(five_perc/total_length*100))
  print("Sub 10%: {0:.2f}%".format(ten_perc/total_length*100))
  print("Sub 15%: {0:.2f}%".format(fifteen_perc/total_length*100))
  print("Sub 20%: {0:.2f}%".format(twenty_perc/total_length*100))
  print("Sub 30%: {0:.2f}%".format(thirty_perc/total_length*100))
  print("Sub 40%: {0:.2f}%".format(fourty_perc/total_length*100))
  print("Sub 50%: {0:.2f}%".format(fifty_perc/total_length*100))
  print("Over 50%: {0:.2f}%".format(over_fifty/total_length*100))

我正在寻找的输出是这样的:

error_distribution(error_dataset1)

输出:

Sub  1%: 16.55%
Sub  5%: 56.61%
Sub 10%: 71.62%
Sub 15%: 78.53%
Sub 20%: 82.97%
Sub 30%: 88.46%
Sub 40%: 91.09%
Sub 50%: 92.59%
Over 50%: 7.41%

有谁知道可以做到这一点的标准库吗?

【问题讨论】:

    标签: python pandas histogram distribution


    【解决方案1】:

    您可以尝试以下方法吗:

    import numpy as np
    arr = np.random.uniform(low=0, high=100, size=(200,))
    count, division = np.histogram(arr, bins=[0, .01, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 1])
    print(count, division)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2022-08-08
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 2018-12-04
      • 2017-10-17
      相关资源
      最近更新 更多