Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mutate data with python pandas library

I have dataframe like

import pandas as pd

x = [
    {
        "timestamp" :1576019484523,
        "status": "1"
    },
    {
        "timestamp" :1576019496337,
        "status": "0"
    },
    {
        "timestamp" :1576019548740,
        "status": "1"
    },
    {
        "timestamp" :1576020996586,
        "status": "0"
    }
]

data_frame = pd.DataFrame(x)

DataFrame
0  1576019484523      1
1  1576019496337      0
2  1576019548740      1
3  1576020996586      0

I want to convert this data like this :

[
    {
        "range" :"1576019484523 - 1576019496337",
        "status": "1"
    },
    {
        "range" : "1576019496337 - 1576019548740",
        "status": "0"
    },
    {
        "range" :"1576019548740 - 1576020996586",
        "status": "1"
    }
]

In case of the number of item count is odd I dont know how to resolve this. If there is any function in pandas I want to know or any function that would help me in python

[t0-t1] status 0
[t1-t2] status 1
[t2-t3] status 0
[t3-t4] status 1
like image 286
Mehmetali Saraç Avatar asked Dec 20 '25 18:12

Mehmetali Saraç


1 Answers

You could do with without the need for pandas - using list comprehension:

[{'range': f"{i['timestamp']} - {j['timestamp']}", 'status': i['status']}
  for i, j in zip(x, x[1:])]

[out]

[{'range': '1576019484523 - 1576019496337', 'status': '1'},
 {'range': '1576019496337 - 1576019548740', 'status': '0'},
 {'range': '1576019548740 - 1576020996586', 'status': '1'}]
like image 183
Chris Adams Avatar answered Dec 23 '25 07:12

Chris Adams



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!