Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
...           ...


MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading