1

I have a column df['Rounds'] that is int64 and the values can be 1-5.

I need to calculate the fight duration ((df[Rounds]-1)*(00:05:00))+df['final_round_duration']

but this did not work.

numpy.core._exceptions.UFuncTypeError: ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')

Rounds final_round_duration fight_duration
1 00:03:00 00:03:00
3 00:02:00 00:12:00
5 00:05:00 00:25:00

1 Answers1

1

Multiply by a pd.Timedelta instead:

import pandas as pd

df = pd.DataFrame({'Rounds': [1, 3, 5],
                   'final_round_duration': ['00:03:00', '00:02:00', '00:05:00']})

# Calculate Duration Time
df['flight_duration'] = (df['Rounds'] - 1) * pd.Timedelta(minutes=5) + \
                        pd.to_timedelta(df['final_round_duration'])

print(df.to_string(index=False))

Output:

Rounds final_round_duration flight_duration
     1             00:03:00 0 days 00:03:00
     3             00:02:00 0 days 00:12:00
     5             00:05:00 0 days 00:25:00

Timedeltas can be reformatted back to just hours, minutes, and seconds

(See. timedelta to string type in pandas dataframe)

import pandas as pd


def format_timedelta(x):
    ts = x.total_seconds()
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f'{int(hours)}:{int(minutes):02d}:{ int(seconds):02d}'


df = pd.DataFrame({'Rounds': [1, 3, 5],
                   'final_round_duration': ['00:03:00', '00:02:00', '00:05:00']})

# Calculate Duration Time
df['flight_duration'] = (
        (df['Rounds'] - 1)
        * pd.Timedelta(minutes=5)
        + pd.to_timedelta(df['final_round_duration'])
).apply(format_timedelta) # Apply Formatting

print(df.to_string(index=False))

Output:

Rounds final_round_duration flight_duration
     1             00:03:00         0:03:00
     3             00:02:00         0:12:00
     5             00:05:00         0:25:00
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57