5 回答
TA贡献2019条经验 获得超9个赞
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
TA贡献1810条经验 获得超5个赞
正如您提到的,它不会超过 1 00:00,即 24:00,有一种更简单的方法:
'''
Person Activity Duration
1 A 1 00:00
2 A 1 00:00
3 B 0 21:17
4 C 0 17:11
'''
import pandas as pd
df = pd.read_clipboard("\t")
.
Person Activity Duration
0 1 A 1 00:00
1 2 A 1 00:00
2 3 B 0 21:17
3 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 Duration
0 1 A 24:00
1 2 A 24:00
2 3 B 21:17
3 4 C 17:11
TA贡献1851条经验 获得超4个赞
您可以轻松地将这些数字相乘和相加:
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))
TA贡献1784条经验 获得超8个赞
您可以使用 datetime 模块进行时间转换
from datetime import datetime
def 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
TA贡献1828条经验 获得超4个赞
除了其他有用的答案之外,我还想发布我自己的解决方案,它使用自定义函数并将其应用于数据框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)
添加回答
举报