How to add Datetime.Time in Pandas by group by?

Asked

Viewed 395 times

1

I have a dataframe with two columns of Total CPU Time and Date, in the format below:

Total Cpu Time: 00:00:14
Date : 2019-02-06

I need to do a group by Date that adds the hours (without disregarding minute and second) of CPU Time. I tried to convert the way below and then give group by, but unsuccessfully.

df['total_cpu_time'] = pd.to_datetime(df['total_cpu_time']).dt.time

Someone has a solution?

1 answer

1


You can convert to datetime and timedelta and then groupby() and sum(). For Plot you need to convert in seconds.

import pandas as pd
import matplotlib.pyplot as plt

data = { 'Total Cpu Time': ['00:00:14', '00:00:15', '00:00:16', '00:00:17'], 'Date': ['2019-02-07', '2019-02-07', '2019-02-08', '2019-02-08'] }

df = pd.DataFrame(data, columns = ['Total Cpu Time', 'Date']) 

df['Date'] = pd.to_datetime(df['Date'])
df['Total Cpu Time'] = pd.to_timedelta(df['Total Cpu Time'])

grouped = df['Total Cpu Time'].groupby(df['Date']).sum()
print(grouped)

grouped.astype('timedelta64[s]').plot.bar(x='Date', y='Total Cpu Time', rot=0)
plt.show()
  • Wonderful! Thank you very much!

  • How would I plot this result? It gives error "No Numeric data to Plot".

  • I edited the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.