add values to a column from a dictionary

Here is one approach. I added date to original data, and changed the time offset from 0 to 1, to verify that all adjustments get applied.

import pandas as pd

df = {'emp': [123, 234], 
      'state': ['AL', 'CA'], 
      'start_time': ['2020-11-05 08:00', '2020-11-05 08:00'], 
      'end_time':   ['2020-11-05 17:00', '2020-11-05 17:00'],
     }
# create data frame
df = pd.DataFrame(data=df)

# convert data type
df['start_time'] = pd.to_datetime(df['start_time'])
df['end_time'] = pd.to_datetime(df['end_time'])

# original adjustments
start_adjust = {"AL": 1, "CA": 20}

# convert data type
start_adjust = {
    key: pd.to_timedelta(value, unit='minute')
    for key, value in start_adjust.items()
}

# apply adjustment
df['start_time'] += df.apply(lambda x: start_adjust[x['state']], axis=1)

# results
print(df)

   emp state          start_time            end_time
0  123    AL 2020-11-05 08:01:00 2020-11-05 17:00:00
1  234    CA 2020-11-05 08:20:00 2020-11-05 17:00:00

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top