Home > Software design >  Increment a time and add it in data frame column
Increment a time and add it in data frame column

Time:11-10

Hi I am new to python and I am looking for below result.

I have From_Curr(3), To_Curr(3) and making currency pairs and adding new column in my data frame as time.

3*3 = 9 currency pairs created So I want same time for currency pairs and then increment by 1 hr again for same pairs as shown below.

Problem statement is time gets incremented after every row.

Actual df:

enter image description here

Expected df:

enter image description here

Thanks for any help and appreciate your time.

`

import pandas as pd
import datetime
from datetime import timedelta
data = pd.DataFrame({'From':["EUR","GBP",'USD'],
                    'To':["INR","SGD",'HKD'],
                    'time':''})


init_date = datetime.datetime(1, 1, 1)
for index, row in data.iterrows():
    row['time'] = str(init_date)[11:19]
    init_date = init_date   timedelta(hours=1.0)

`

CodePudding user response:

I'm not understanding why you are repeating the combinations, and incrementing in one hour in the last half.

But for this case, you can do something like this:

import pandas as pd

data = pd.DataFrame({'From':["EUR","GBP",'USD'],
                    'To':["INR","SGD",'HKD'],
                    'time':''})
outlist = [ (i, j) for i in data["From"] for j in data["To"] ]*2 # Create double combinations
data = pd.DataFrame(data=outlist,columns=["From","To"])
data["time"] = "00:00:00"
data["time"].iloc[int(len(data)/2):len(data)] =  "01:00:00" # Assign 1 hour to last half
data["time"] = pd.to_datetime(data["time"]).dt.time

Update: After some clarifications

import pandas as pd

data = pd.DataFrame(
    {"From": ["EUR", "GBP", "USD"], "To": ["INR", "SGD", "HKD"], "time": ""}
)
outlist = [
    (i, j) for i in data["From"] for j in data["To"]
] * 2  # Create double combinations, i think that for your case it would be 24 instead of two
data = pd.DataFrame(data=outlist, columns=["From", "To"])
data["time"] = data.groupby(["From", "To"]).cumcount()  # Get counts of pairs values
data["time"] = data["time"] * pd.to_datetime("01:00:00").value # Multiply occurrences by the value of 1 hour
data["time"] = pd.to_datetime(data["time"]).dt.time # Pass to time

I think this script covers all your needs, happy coding :)

Regards,

  • Related