1

How do you calculate an average top or bottom 'n' Values in Python? Example below, column = c2 calculates the average of the top 2 in the last 4 days.

c0     c1     c2
1     2      na
2     2      na
3     3      na
4     5      4
5     6      5.5
6     7      6.5
7     5      6.5
8     4      6.5
9     5      6
10    5      5
Seanny123
  • 8,776
  • 13
  • 68
  • 124
mark
  • 95
  • 11

2 Answers2

1

Sort the list, get the sum of the last n numbers and divide it by n:

def avg_of_top_n(l, n):
    return sum(sorted(l)[-n:]) / n
l = [2, 2, 3, 5, 6, 7, 5, 4, 5, 5]
for i in range(4, 11):
    print(avg_of_top_n(l[i - 4: i], 2))

This outputs:

4.0
5.5
6.5
6.5
6.5
6.0
5.0
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Thanks blhsing. Its working, but I am not able to add it to the original dataframe. def avg_of_top_n(l, n): return sum(sorted(l)[-n:]) / n l = data['list'] for i in range(4, 11): data['top'] = avg_of_top_n(l[i -4: i], 2) – mark Jul 22 '18 at 00:28
0

You could first sort a list of values, then grab the first n values into a new list. Then average them by diving the sum of the list by the number of values in the list.

n = 2
new_list = [1,5,4,3,2,6]
new_list.sort()
top_vals = new_list[:n]
top_vals_avg = sum(top_vals) / float(len(top_vals))
ryansin
  • 1,735
  • 2
  • 26
  • 49