Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

python - How can i get the average delivery time (stored as timedelta64[ns]) per day on Pandas?

So, i have the following data frame on pandas:

enter image description here

I need to create another data frame with the average delivery time by day, by i'm having a hardtime with this task.

So, as you can see, I have all the 365 days of 2018 and I need to calculate what was the average time the user had to wait before getting his order delivered. I only need the hours, minutes and seconds, because the number of days will never be grater than 0. And the delivery time is timedelta64 format.

Thank you folks!

question from:https://stackoverflow.com/questions/65872018/how-can-i-get-the-average-delivery-time-stored-as-timedelta64ns-per-day-on-p

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

User groupby and mean

import pandas as pd
from io import StringIO

#Data preprocessing(ignore)
data = StringIO('''
2018-01-01 ,0 days 00:58:26 
2018-01-01 ,0 days 01:27:04 
2018-01-01 ,0 days 00:17:27 
2018-01-01 ,0 days 00:14:26 
2018-01-01 ,0 days 01:08:33 
''')

#Converting to datetime and timedelta object
df = pd.read_csv(data,names=['date','delivery_time'],parse_dates=['date'])
df['delivery_time'] = pd.to_timedelta(df['delivery_time'])

#Grouping by date and then finding mean of delivery time
df.groupby(['date']).mean(numeric_only=False)

Output:

            delivery_time
date    
2018-01-01  0 days 00:49:11.200000

using dt.components you can easily extract hours minutes and seconds from your timedelta column. Something like following should generate your result.

df.groupby(['date']).mean(numeric_only=False)['delivery_time'].dt.components.iloc[:, 1:4]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...