0

Following the StackOverflow post Elegantly calculate mean of first three values of a list I have tweaked the code to find the maximum.

However, I also require to know the position/index of the max. So the code below calculates the max value for the first 3 numbers and then the max value for the next 3 numbers and so on.

For example for a list of values [6 3 7 4 6 9 2 6 7 4 3 7 7 2 5 4 1 7 5 1]. The code below takes the first 3 values 6,3,7 and outputs the max as 7 and then for the next 3 values 4,6,9 outputs the value 9 and so on.

But I also want to find which position/index they are at, 1.e 7 is at position 2 and 9 at position 5. The final result [2,5,8,11,12,...]. Any ideas on how to calculate the index. Thanks in advance.

import numpy as np
np.random.seed(42)
test_data = np.random.randint(low = 0, high = 10, size = 20)
maxval = [max(test_data[i:i+3]) for i in range(0,len(test_data),3)]

print(test_data)
print(maxval)

output: test_data : [6 3 7 4 6 9 2 6 7 4 3 7 7 2 5 4 1 7 5 1]
output: [7, 9, 7, 7, 7, 7, 5]
cwliang
  • 135
  • 11
imantha
  • 2,676
  • 4
  • 23
  • 46

1 Answers1

1
import numpy as np
np.random.seed(42)
test_data = np.random.randint(low = 0, high = 10, size = 20)

maxval = [max(test_data[i:i+3]) for i in range(0,len(test_data),3)]
index = [(np.argmax(test_data[i: i+3]) + i) for i in range(0,len(test_data),3)]

print(test_data)
print(maxval)
print(index)
Sachin Patel
  • 499
  • 2
  • 12