Dominic Demeterfi
Dominic Demeterfi

Reputation: 3

Numpy Arrays based on threshold criteria from a list

I need to take a list with 7000 elements, the values range from ~ -150 to 150, and it cycles back and forth. Every time the value crosses a threshold of -50 I need to include all the values in an array until it crosses -50 again. I need to make an array for each of these cycles and then count how many arrays are made and find the mean of how many elements each of these arrays has.

Upvotes: 0

Views: 249

Answers (1)

dannyadam
dannyadam

Reputation: 4170

The following code 1) calculates the indices where the next element crosses -50, 2) splits the array at elements that crossed -50, 3) counts how many arrays there are after splitting, and 4) calculates the mean of each split.

import numpy as np
array = np.array([...])
crossings = np.where(np.diff(np.sign(array + 50)))[0]
splits = np.split(array, crossings + 1)
count = len(splits)
means = [x.mean() for x in splits]

Upvotes: 0

Related Questions