Convert MM:SS To Seconds in Multiple Columns of DataFrame

时间:2019-04-17 01:20:06

标签: pandas python-datetime

I have a DataFrame with multiple columns containing data that is formatted in minutes and seconds (i.e. 9:17), and I want to convert that into seconds (i.e. 9:17 becomes 557).

I've tried using the DateTime lib in Python 3.x to convert to seconds; however, I keep getting miscellaneous errors.

Here is how I'm trying to do it:

player_production_data = pd.merge(player_basic_data, player_toi_data[['Year', 'Player', 'Tm', 'Avg Shift', 'EV TOI', 'EV CF Rel', 'EV GF/60', 'EV GA/60',
'PP TOI', 'PP CF Rel', 'PP GF/60', 'PP GA/60', 'SH TOI', 'SH CF Rel', 'SH GF/60', 'SH GA/60']], on = ['Year', 'Player', 'Tm']) 

# Convert TOI Data to seconds
player_production_data[['ATOI', 'Avg Shift', 'PP TOI', 'SH TOI']] = pd.to_datetime(player_production_data[['ATOI', 'Avg Shift', 'PP TOI', 'SH TOI']],format='%M:%S')

Where player_production_data is the DataFrame and the columns I'm trying do do this transformation on are ATOI, Avg Shift, PP TOI, and SH TOI

The error for this specific function is ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

Thank you for any help!

1 个答案:

答案 0 :(得分:0)

Convert to timedelta, then call total_seconds. You can do this with a single to_timedelta call thanks to stack/unstack:

cols = ['ATOI', 'Avg Shift', 'PP TOI', 'SH TOI']
df[cols] = (pd.to_timedelta(df[cols].stack() + ':00', errors='coerce')
              .dt.total_seconds()
              .unstack())