如何将DataFrame中的24小时制时间列转换为总秒数?
Hey there! Converting a HH:MM:SS time string column to total seconds in pandas is straightforward—here are a couple of clean, efficient ways to do it, using your sample data as a starting point.
First, let's complete your sample DataFrame code (since it was cut off) so we have a runnable example:
import pandas as pd import random def randomTime(): rtime = int(random.random()*86400) hours = int(rtime/3600) minutes = int((rtime - hours*3600)/60) seconds = rtime - hours*3600 - minutes*60 time_string = '%02d:%02d:%02d' % (hours, minutes, seconds) return time_string time = [randomTime() for _ in range(8)] events = ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'] # Completed the Events list df = pd.DataFrame({'Time': time, 'Events': events}) print(df)
Method 1: Use pd.to_timedelta (Simplest & Most Efficient)
This is the go-to method—it directly converts your time string to a timedelta object, then we can grab the total seconds with total_seconds():
df['Total_Seconds'] = pd.to_timedelta(df['Time']).dt.total_seconds() print(df)
Method 2: Manual Calculation (If You Want to Break It Down)
If you prefer to see the individual components (hours, minutes, seconds) used in the calculation, here are two ways to do that:
Option A: Split the Time String
Split the HH:MM:SS string into separate columns, convert them to integers, then compute the total seconds:
# Split the Time column into hours, minutes, seconds df[['Hours', 'Minutes', 'Seconds']] = df['Time'].str.split(':', expand=True).astype(int) # Calculate total seconds df['Total_Seconds'] = df['Hours'] * 3600 + df['Minutes'] * 60 + df['Seconds'] # Optional: Remove the intermediate columns if you don't need them df = df.drop(['Hours', 'Minutes', 'Seconds'], axis=1) print(df)
Option B: Use Datetime Conversion
Convert the time string to a datetime object (we can ignore the date part since we only care about time), then extract the hour, minute, and second values to compute total seconds:
# Convert Time to datetime format (using a dummy date under the hood) df['Time_Datetime'] = pd.to_datetime(df['Time'], format='%H:%M:%S') # Calculate total seconds from datetime components df['Total_Seconds'] = df['Time_Datetime'].dt.hour * 3600 + df['Time_Datetime'].dt.minute * 60 + df['Time_Datetime'].dt.second # Optional: Drop the datetime column df = df.drop('Time_Datetime', axis=1) print(df)
All these methods will give you the total number of seconds since midnight for each time entry. Method 1 is the most concise and performs best for large datasets.
内容的提问来源于stack exchange,提问作者user9394674

