[英]How do I find the average time?
I am currently working on this project and have some issues finding the average time based on their corresponding types.我目前正在研究这个项目,但在根据相应类型查找平均时间时遇到了一些问题。 For now, I have my output as shown below after reading my CSV file.现在,在阅读我的 CSV 文件后,我的输出如下所示。
#Following this format (x typeList : timeTakenList)
0 Lift : 5 days, 5:39:00
1 Lift : 5 days, 5:31:00
2 lighting : 3 days, 9:47:00
3 ACMV : 5 days, 5:21:00
4 lighting : 3 days, 9:32:00
.
.
.
How do I calculate the average time taken for each type such that I have the following output?如何计算每种类型所花费的平均时间,以便获得以下输出?
0 Lift : (5 days, 5:31:00 + 5 days, 5:39:00) / 2
1 lighting : (3 days, 9:47:00 + 3 days, 9:32:00) / 2
2 ACMV : 5 days, 5:21:00
.
.
.
The timeTakenList is calculated from subtracting another column, Acknowledged Date from the column CompletedDate. timeTakenList 是通过从 CompletedDate 列中减去另一列 Acknowledged Date 计算得出的。
timeTakenList = completedDate - acknowledgedDate
There is a ton of other types in the typeList and I'm trying to avoid doing an if statement like if typeList[x] == "Lift", then add the time together, etc. typeList 中有大量其他类型,我试图避免执行 if typeList[x] == "Lift" 之类的 if 语句,然后将时间加在一起等。
Example of .csv file: .csv 文件示例:
I'm not too sure how else to make my question clearer, but any help is much appreciated.我不太确定如何使我的问题更清楚,但非常感谢任何帮助。
check the below implementation.检查下面的实现。
import re
typeList = ["Lighting", "Lighting", "Air-Con", "Air-Con", "Toilet"]
timeTakenList = ["10hours", "5hours", "2days, 5hrs", "5hours", "4hours"]
def convertTime(total_time):
li = list(map(int,re.sub(r"days|hrs|hours","",total_time).split(",")))
if len(li) == 2:
return li[0] * 24 + li[1]
return li[0]
def convertDays(total_time):
days = int(total_time / 24)
hours = total_time % 24
if (hours).is_integer():
hours = int(hours)
if days == 0:
return str(hours) + "hours"
return str(days) + "days, " + str(hours) + "hrs"
def avg(numbers):
av = float(sum(numbers)) / max(len(numbers), 1)
return av
avgTime = {}
for i, types in enumerate(typeList):
if avgTime.has_key(types):
avgTime[types].append(convertTime(timeTakenList[i]))
else:
avgTime[types] = [convertTime(timeTakenList[i])]
for types in avgTime.keys():
print types + " : " + convertDays(avg(avgTime[types]))
Algo算法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.