python - 寻找平均持续时间(H :M:S) in python pandas

标签 python pandas datetime mean

我试图在 Pandas 数据框中找到平均持续时间。我尝试了以下代码并收到错误:

TypeError: Could not convert 1:10:4200:38:5800:42:142:30:4100:19:22 to numeric

代码:

import pandas as pd

duration=['1:10:42','38:58','42:14','2:30:41','19:22']
dist=[8,5,6,17,3]
dd=list(zip(duration,dist))
df=pd.DataFrame(dd,columns=['duration','dist'])
print(df)
print('')
max_dist=df['dist'].max()
mean_dist=df['dist'].mean()
df['duration'] = df['duration'].apply(lambda x: x if len(str(x)) ==7 else '00:'+str(x)) 
print(df['duration'])
pd.to_datetime(df['duration'],format='%H:%M:%S').dt.time
max_duration=df['duration'].max()
mean_duration=df['duration'].mean()
print('')
print('max dist =',max_dist,'ave dist =',mean_dist)
print('max duration =',max_duration,'ave duration =',mean_duration)

最大持续时间返回正确的值。错误消息是否意味着日期时间格式不能用于平均值,还是我缺少另一种方式?任何帮助表示赞赏。

最佳答案

pd.to_timedelta 之后赋值并找到均值,即

df['duration'] = pd.to_timedelta(df['duration'])
print('max duration =',max_duration,'ave duration =',df['duration'].mean())

输出:

max duration = 02:30:41 ave duration = 0 days 01:04:23.400000

关于python - 寻找平均持续时间(H :M:S) in python pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619945/

相关文章:

java - 如何从java检查python是否安装在windows中?

python - pytest 获取当前测试文件的文件路径

pandas - 如何按具有 NaN 值的多个(即所有可用)属性对条目进行分组?

pandas - 获取每 4 行的平均值

python - 将时间添加到python中的现有文件

Python strftime 德语日期字符串

Python 抽象基类 : Why doesn't abc prevent instantiation?

python - 这些 for 循环可以重构吗?

python - Pandas to_json 改变数据类型

python 和 Pandas : Convert series of datetime-values to consecutive day-indices