How to calculate the frequency of object array in python

Viewed 41

I have a json array with boolean element and it's time.

[{value:1,time:"2022-01-02 10:15:12"},{value:0,time:"2022-01-02 10:20:12"},{value:1,time:"2022-01-02 10:25:12"},...]

How could I calculate it's frequency in python?

2 Answers

IIUC, you can load the list as DataFrame, slice the time column, convert to_datetime and compute the successive differences with diff.

Then it's unclear if the step should be equal for all or not, so you can either pick the first value, or the mean, or the mode… depending on what you want:

l = [{'value':1,'time':"2022-01-02 10:15:12"},
     {'value':0,'time':"2022-01-02 10:20:12"},
     {'value':1,'time':"2022-01-02 10:25:12"}]

freq = pd.to_datetime(pd.DataFrame(l)['time']).diff().mean()

output: Timedelta('0 days 00:05:00')

I assume here you only want to measure how many times did the True boolean value happened within the period of the measurements:

from datetime import datetime

l = [{"value":1,"time":"2022-01-02 10:15:12"},{"value":0,"time":"2022-01-02 10:20:12"},{"value":1,"time":"2022-01-02 10:25:12"}]

date_lists = [datetime.fromisoformat(x["time"]) for x in l if x["value"]] # datetime list of 1 values
f = 1/(max(date_lists) - min(date_lists)).seconds # frequency: number of positive values between the min-max times

output:

0.0016666666666666668

There is a delta of 10 minutes between the first and last positive values in l, so here f = 1/(600s)

Related