我有下面的示例输入表。
Time
列的格式为 hh:mm:ss
或小时、分钟和秒。
姓名 | 时间 |
---|---|
吉姆 | 1:33:04 |
克丽丝 | 0:06:39 |
比利 | 10:00:02 |
创建上表的代码是:
import pandas as pd
df = pd.DataFrame({'Name':["Jim","Chrissy","Billy"], 'Time':['1:33:04', '0:06:39', '10:00:02']})
我想创建一个名为“_timemin”的新列,将时间列转换为分钟。例如,10:00:02 等于 600.03 分钟。
我尝试应用以下代码,但没有成功:
df['_timemin'] = df['Time'].str.split(':').apply(lambda x: (int(x[0])*60) + int(x[1])) + int(x[2]/60)
...上面的代码产生错误:
NameError: name 'x' is not defined
这是一个示例,说明如何使用日期时间模块来获取时间并将其转换为分钟:
import pandas as pd
from datetime import datetime
# Sample DataFrame
data = {'Time': ['01:30:45', '02:15:20', '00:45:10']} # Sample 'Time' data
df = pd.DataFrame(data)
# Function to convert HH:MM:SS format to minutes
def time_to_minutes(time_str):
time_obj = datetime.strptime(time_str, "%H:%M:%S")
total_minutes = time_obj.hour * 60 + time_obj.minute + time_obj.second / 60
return total_minutes
# Applying the function to the DataFrame's 'Time' column
df['_timemin'] = df['Time'].apply(time_to_minutes)
print(df)
你的表情
df['_timemin'] = df['Time'].str.split(':').apply(lambda x: (int(x[0])*60) + int(x[1])) + int(x[2]/60)
有三个问题:
这里有两个选项:
df['_timemin'] = df['Time'].str.split(':').apply(lambda x: int(x[0]) * 60 + int(x[1]) + int(x[2]) // 60)
四舍五入到分钟
df['_timemin'] = df['Time'].str.split(':').apply(lambda x: int(x[0]) * 60 + int(x[1]) + int(x[2]) / 60)
浮动分钟