0

Is there way we can split a row into multiple rows based on an integer cap value? I have a dataframe as below

sys_df = pd.DataFrame([{'dateTime': '2020-11-12 17:45:00', 'timeTakenInSeconds': 650, 'id':'xyz'}])
Index dateTime timeTakenInSeconds id
0 2020-11-12 17:45:00 650 xyz

I am trying to split the above row into 3 rows of previous 5 minute intervals like below.

Index dateTime timeTakenInSeconds id
0 2020-11-12 17:45:00 300 xyz
1 2020-11-12 17:40:00 300 xyz
2 2020-11-12 17:35:00 50 xyz

Do we have any pandas builin utils to achieve this?

1 Answer 1

1

You can build your own method. A lead can be:

import pandas as pd
from datetime import datetime, timedelta
origin_data = {'dateTime': '2020-11-12 17:45:00', 'timeTakenInSeconds': 650, 'id':'xyz'}

def splitter(origin_data, interval=0):
    data=[]
    to_sec = interval*60
    current_time = datetime.fromisoformat(origin_data['dateTime'])
    for item in range((origin_data['timeTakenInSeconds']//to_sec)):
        data.append({'dateTime': str(current_time),
                     'timeTakenInSeconds': to_sec, 'id':'xyz'})
        current_time -= timedelta(seconds=to_sec)
    reminder = origin_data['timeTakenInSeconds'] - (origin_data['timeTakenInSeconds']//to_sec)*to_sec
    if reminder:
        data.append({'dateTime': str(current_time),
                     'timeTakenInSeconds': reminder, 'id': 'xyz'})
    return data


print(pd.DataFrame(splitter(origin_data, interval=5)))

Outputs:

              dateTime  timeTakenInSeconds   id
0  2020-11-12 17:45:00                 300  xyz
1  2020-11-12 17:40:00                 300  xyz
2  2020-11-12 17:35:00                  50  xyz

Note:

You can also use:

pd.date_range(end=datetime.fromisoformat(origin_data['dateTime']), periods=3, freq='5min')

To split the date as you wish.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.