Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill in missing values in lists

Tags:

python

Lets say I have 2 lists of data related to a time stamp and a number so:

list1 = ['00:00:02', '00:00:05', '00:00:06']
list2 = [2,3,4]

I want to essentially fill in the missing time stamps to the rest of the day and have a '0' for any time there is not a coreseponding number to the time stamp, assuming the times match the number sin list1 and list2. So we get:

list1 = ['00:00:02', '00:00:05', '00:00:06']
list2 = [2,3,4]

list3 = ['00:00:00', '00:00:01', '00:00:02', '00:00:03', '00:00:04', '00:00:05', '00:00:06']
list4 = [0,0,2,0,0,3,4]

Been trying to conceptualize how to do this any can't think of anything logical.

like image 329
JSimonsen Avatar asked Aug 22 '26 15:08

JSimonsen


1 Answers

Instead of having hard-coded lists you could have a generator to yield each pair:

from functools import reduce

def base60(ts):
    """Parses the timestamps HH:MM:SS into monotonic integer numbers"""
    return reduce(lambda acc, v: acc * 60 + int(v), ts.split(":"), 0) 

def to_ts(v):
    """Convert a single integer representing a "base 60" HH:MM:SS timestamp into a timestamp sting"""
    parts = []
    while v:
        parts.insert(0, "{:02d}".format(v % 60))
        v //= 60
    return ":".join((["00"] * (3 - len(parts))) + parts)

def timeseries(timestamps, values):
    counter = 0
    for timestamp, value in zip(timestamps, values):
        target = base60(timestamp)
        while counter < target:
            # While internal counter is less than the next
            # timestamp in the given series, 
            # yield the counter and a value of zero. 
            yield to_ts(counter), 0
            counter += 1
        yield timestamp, value
        counter += 1

And if you really need the result as two separate static sequences (although zip yields tuples rather than lists):

list3, list4 = zip(*timeseries(list1, list2))
like image 69
jsbueno Avatar answered Aug 25 '26 04:08

jsbueno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!