gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:27 24 4
gpt4 key购买 nike

我试图在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com