Search code examples
pythonpandastime-series

Python : Convert a dataframe of events into a square wave time serie


How would you transform a pandas dataframe composed of successive events:

start_time | end_time | value

1671221209   1671234984   2000
1671240425   1671241235   1000
1671289246   1671289600   133
...          ...          ...

into timeserie like this:

     time |  value

1671221209    2000
1671234984    2000
1671234985    0
1671240424    0
1671240425    1000
1671241235    1000
1671241236    0
1671289245    0
1671289246    133
1671289600    133
1671289601    0
...           ...



Solution

  • You can use melt function:

    result = (
        df.melt(id_vars='value', var_name='time_type', value_name='time')
        .drop(columns=['time_type'])
        .sort_values(by='time')
        .reset_index(drop=True)
    )
    
    result = result[['time', 'value']]