Kenneth Yeung
Kenneth Yeung

Reputation: 35

Python pandas column convert minutes to second

I have pandas like below:

    Runner  time
1   A      3.05.3   #( 3 minute 5 second and 3 millisecond)
2   B      2.50.2   #( 2 minute 50 second and 2 millisecond)

Actually I want to compare the time so I want to change to time column to second unit or millisecond unit.
How can I do it in pandas?
I am thinking if can I strptime?

Upvotes: 3

Views: 5603

Answers (2)

jpp
jpp

Reputation: 164623

You can use datetime.timedelta to perform this calculation for you. For convenience, you can wrap this in a function and apply via pd.Series.apply.

from datetime import timedelta

df = pd.DataFrame({'Runner': ['A', 'B'],
                   'time': ['3.05.3', '2.50.2']})

def seconder(x):
    mins, secs, millis = map(float, x.split('.'))
    td = timedelta(minutes=mins, seconds=secs, milliseconds=millis)
    return td.total_seconds()

df['seconds'] = df['time'].apply(seconder)

print(df)

  Runner    time  seconds
0      A  3.05.3  185.003
1      B  2.50.2  170.002

Upvotes: 1

jezrael
jezrael

Reputation: 862481

Use for seconds list comprehension with converting to int if no NaNs values:

df['new'] = [int(a) * 60 + int(b) + int(c) / 1000 for a,b,c in df['col2'].str.split('.')]

Another solution is split values with expand=True for DataFrame and process it:

df1 = df['col2'].str.split('.', expand=True).astype(int)
df['new'] = df1[0] * 60 + df1[1] + df1[2] / 1000

print (df)
  col1    col2      new
0    A  3.05.3  185.003
1    B  2.50.2  170.002

And for miliseconds multiple by 1000:

df['new'] *= 1000
print (df)
  col1    col2       new
0    A  3.05.3  185003.0
1    B  2.50.2  170002.0

Upvotes: 0

Related Questions