3

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

your answer also working, you also let me know can apply function in the pandas thx
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.