-
慕少森
a = np.array([24, 1, 1/60]) df.Duration = df.Duration.str.split(' |:', expand=True).astype(int).dot(a)例子:df = pd.DataFrame({'Person': [1,2,3,4], "Activity": list('AABC') ,"Duration":['1 00:00', '1 00:00', '0 21:17', '0 17:11']})df.Duration = df.Duration.str.split(' |:', expand=True).astype(int).dot(a)print(df)# Person Activity Duration#0 1 A 24.000000#1 2 A 24.000000#2 3 B 21.283333#3 4 C 17.183333
-
森栏
正如您提到的,它不会超过 1 00:00,即 24:00,有一种更简单的方法:'''Person Activity Duration1 A 1 00:002 A 1 00:003 B 0 21:174 C 0 17:11'''import pandas as pddf = pd.read_clipboard("\t"). Person Activity Duration0 1 A 1 00:001 2 A 1 00:002 3 B 0 21:173 4 C 0 17:11 .df['Duration'] = df['Duration'].str.split(' ')df['Duration'] = ['24:00' if int(val[0]) == 1 else val[1] for val in df['Duration']]print(df). Person Activity Duration0 1 A 24:001 2 A 24:002 3 B 21:173 4 C 17:11
-
繁花不似锦
您可以轻松地将这些数字相乘和相加:durations = [ "1 00:00", "0 21:17", ] for duration in durations: day, clock = duration.split() hour, minute = clock.split(':') print((int(day) * 24) + int(hour) + (int(minute) / 60))
-
青春有我
您可以使用 datetime 模块进行时间转换from datetime import datetimedef durationInDecimal(string): day, time = string.split(" ") t = datetime.strptime(time, "%H:%M").time() return int(day)*24 + (t.hour+t.minute/60.0)df = pd.DataFrame({'Person': list("ABCD"), "Activity": list('ABCD') ,"duration":['1 00:00', '1 00:00', '0 21:17', '0 17:11']})df["duration"] = df.duration.apply(durationInDecimal)# Person Activity duration# 0 A A 24.000000# 1 B B 24.000000# 2 C C 21.283333# 3 D D 17.183333
-
明月笑刀无情
除了其他有用的答案之外,我还想发布我自己的解决方案,它使用自定义函数并将其应用于数据框df.apply:def custom_time_to_decimals(value): if value.split()[0]=='1': return 24 else: custom = value.split()[1] hours = int(custom[0:2]) minutes = int(custom[3:5]) decimal = hours + (minutes/60) return round(decimal,3)df['decimalHours'] = df['<insertYourTimeColumnHere>'].apply(custom_time_to_decimals)