1

I want to convert the AVG column's numbers to hour(s):minute(s) form.

  • if it is more than 24h, I still want only hour:minutes form like this 73:45
  • consider these numbers as seconds

plus I want to show the AVG time of these activities on a bar. All the activities. I us this for it:

df2 = df.groupby(['Activity']).mean()

I want to see the hour:minutes

df = pd.read_csv('practice.csv')

df['AVG'] = df['AVG'].astype('datetime64[ns]')

out:

Activity AVG 0 sleep 1970-01-01 00:00:00.000000221 1 sleep 1970-01-01 00:00:00.000000201 2 swim 1970-01-01 00:00:00.000000300 3 run 1970-01-01 00:00:00.000001768 4 tv 1970-01-01 00:00:00.000000105

ptr808
  • 25
  • 5

1 Answers1

0

First aggregate mean, convert column to timedeltas and format it in custom function:

df2 = df.groupby('Activity', as_index=False)['AVG'].mean()

#https://stackoverflow.com/a/51102096/2901002
def f(x):
    ts = x.total_seconds()
    hours, remainder = divmod(ts, 3600)
    minutes, seconds = divmod(remainder, 60)
    return ('{}:{:02d}').format(int(hours), int(minutes)) 


df2['AVG'] = pd.to_timedelta(df2['AVG'], unit='s').apply(f)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • raise TypeError("no numeric data to plot") TypeError: no numeric data to plot but I think I am getting it.. so, I will try something – ptr808 Jan 02 '23 at 11:48
  • @ptr808 - If need plotting use seconds, but if need hours or minutes use [this](https://stackoverflow.com/questions/45892320/how-to-plot-timedelta-data-from-a-pandas-dataframe) solution without `.apply(f)` – jezrael Jan 02 '23 at 12:13
  • I cannot solve it. I do not understand. – ptr808 Jan 02 '23 at 16:45
  • https://drive.google.com/file/d/1v36C7g8OWeI0MHzuVknM5hWoW4Bhr4Yk/view?usp=drivesdk – ptr808 Jan 02 '23 at 17:08