I have a data-frame something like this:
And I wish to find the the location (start and end) and the average of the stretch of stretch where values in column 2 are more than 0.2. Something like this:
Assuming you are using pandas
this could be done as follows:
import pandas as pd
df = pd.DataFrame({
"value": [0.28, 0.26, 0.22, 0.14, 0.16, 0.14, 0.10, 0.18, 0.30, 0.32, 0.30, 0.24, 0.08, 0.08, 0.10]
})
(
df
# check if values are sequential and above/below the treshold
.assign(range = lambda x: (x["value"] < 0.20).cumsum())
# drop the extra rows below with values below the treshold
.loc[lambda x: x["value"] > 0.20]
.reset_index()
# group by the sequence number and aggregate
.groupby("range")
.agg({"index": ["min", "max"], "value": "mean"})
# reset index and drop extra column
.reset_index()
.drop("range", axis=1)
)
Which gives the following dataframe as output:
# index value
# min max mean
# 0 0 2 0.253333
# 1 8 11 0.290000