将 hh:mm:ss 格式的时间转换为 pandas 的总分钟数

问题描述 投票:0回答:3

我有下面的示例输入表。

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
python pandas time type-conversion calculated-columns
3个回答
0
投票

这是一个示例,说明如何使用日期时间模块来获取时间并将其转换为分钟:

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)

0
投票

如果时间小于 24 小时(似乎是根据给定输入推断的),我们可以将

Time
列转换为以秒为单位的 timedelta 对象,并将 that 转换为分钟。

df = pd.DataFrame({
    'Name':["Jim","Chrissy","Billy"], 
    'Time':['1:33:04', '0:06:39', '10:00:02']})
df['_timemin'] = pd.to_timedelta(df['Time']).dt.total_seconds() / 60


0
投票

你的表情

df['_timemin'] = df['Time'].str.split(':').apply(lambda x: (int(x[0])*60) + int(x[1])) + int(x[2]/60)
有三个问题:

  1. 不关闭apply方法
  2. 对前两个元素(仅 x[0] 和 x[1])应用(关闭 lambda x)
  3. 除法之前不将字符串 x[2] 转换为数值数据类型

这里有两个选项:

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)
浮动分钟

© www.soinside.com 2019 - 2024. All rights reserved.