Home > other >  In Pyton im tring to convert a whole dataset of hr:min:secs into seconds
In Pyton im tring to convert a whole dataset of hr:min:secs into seconds

Time:04-08

I'm trying to get the function i made to apply to columns I specified by separating in the iloc function

# Import useful packages for data science
import numpy as np
import pandas as pd
import os
import sys
import time
import datetime
import time

#setting the triathlone data set as TD

TD=pd.read_csv("/Applications/TriathloneData.csv")


TD

def hms_to_seconds(t):
    if(type(t) != str):
        return np.NaN
    else:
        h, m, s = [int(i) for i in t.split(':')]
        return 3600*h   60*m   s

# first I'll separate each column I need to apply the function to
TDdf = pd.DataFrame(TD)
TDdfTime = TDdf.iloc[:,6:12]

TDdfTime

CodePudding user response:

You can do this pretty easily with the .apply() function available to pandas DataFrames. You can find your answer here: https://stackoverflow.com/a/34962199/8222441. Instead of using a lambda however, you can just pass your function. Hope this helps!

CodePudding user response:

You can convert your date column to Datetime object and use total_seconds of timedelta object to get total seconds

df['date'] = pd.to_datetime(df['date'])
df['seconds'] = df['date'].dt.time.astype(str).apply(pd.to_timedelta).dt.total_seconds()
  • Related