I have a dataframe of 15 columns, 9 of them are strings in duration format (hh:mm:ss) that I need to convert them into seconds (int). I am still new with pandas and python and wrote the below code.
#Example df
df = pd.DataFrame({'column_1':['00:12:21','01:20:01'],'column_2':['00:22:33','02:10:11']})
def duration_to_sec(x):
if len(x.split(':')) == 3 :
h,m,s = x.split(':')
x = (int(h)*60*60)+(int(m)*60)+(int(s))
else : x=0
return x
new_col = []
for i in df['column_1']:
x = duration_to_sec(i)
new_col.append(x)
df['column_1'] = pd.Series(new_col)
print(df)
Expected output (same as column_1)
column_1 column_2
0 741 00:22:33
1 4801 02:10:11
it is working fine but it is really basic and I have to declare the function multiple times for the 9 columns. so what is the simpler and cleaner methods to apply here?