如何找到大熊猫中一定范围内的价值计数?

时间:2019-02-11 04:15:57

标签: python pandas histogram distribution

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

enter image description here

到目前为止,我已经看过诸如pd.cut()和plt.hist()之类的函数,但是似乎没有库可以给我答案,因为我的范围相互重叠,因此我不得不诉诸很长的习惯取得的功能-如下:

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%

有人知道标准库可以做到吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法吗?

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)