I have a DF with time given as hours, minutes or milliseconds. The time column has the type float and the time_unit column indicate if it is given as hour, minute or ms.
I want to create a a new column that calculates the amount of seconds. Thus, I need a function that first checks what time_unit it is, then takes the value from time and performs some transformation to seconds.
For example:
if df["time_unit"]="h":
return df["time"]*60*60 # given hours as int
elseif: ...
My df looks like this:
I want to create the green column (seconds). So, how do I do this in pandas?
CodePudding user response:
You can create the mapping dict
d = {'h' : 60*60, 'min' : 60, 'ms' : 1/1000}
df['seconds'] = df['time_unit'].map(d) * df['time']
CodePudding user response:
seconds = []
for i,r in df.iterrows():
if r['time_unit'] == 'h':
seconds.append(r['time']*3600)
elif r['time_unit'] == 'min':
seconds.append(r['time']*60)
elif r['time_unit'] == 'ms':
seconds.append(r['time']/1000)
df['seconds'] = seconds
I guess this will work.