I have the following data array:
import pandas as pd
import numpy as np
array = np.array([10, 20, 100, 6, -3, -4, 7, 100, -7, -99, 88])
I would like to calculate the number of times that the elements of the array cross the value of an average.
What I tried to do was:
# Initially, I defined an average variable:
Mean = 51.5
# I tried to develop a function to do this calculation:
def zero_crossing_avg(data):
output = []
running_total = data[0]
count = 1
for i in range(1, data.size):
val = data[i]
if val - data[i-1] < Mean:
running_total += val
count += 1
else:
output.append(round(running_total/count))
running_total = val
count = 1
return (len(output))
This function is not returning the correct value.
For example:
zero_crossing_avg(array)
Passing the array as an argument the output is: 3, but the desired output is: 5.
Explanation:
#from 20 to 100 it passed the average (+1).
#from 100 to 6 passed the average (+1).
#from 7 to 100 passed the average (+1).
#from 100 to -7 passed the average (+1).
#from -99 to 88 passed the average (+1)
Total = 5
If you're using numpy, you won't need a loop for this:
import numpy as np
array = np.array([10, 20, 100, 6, -3, -4, 7, 100, -7, -99, 88])
mean = 51.5
crossCount = np.sum((array[:-1]>mean) != (array[1:]>mean))
print(crossCount) # 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.