Home > other >  Calculate the row average of a DataFrame and round up
Calculate the row average of a DataFrame and round up

Time:07-08

Be the following pandas DataFrame in Python:

Hours 2022-06-06 2022-06-07 2022-06-08 2022-06-09 2022-06-10 2022-06-13 2022-06-14 2022-06-15 2022-06-16 2022-06-17
00:00 3 0 0 3 23 2 3 3 7 3
05:00 5 4 0 3 32 9 3 3 5 3
10:00 0 3 3 34 45 6 3 0 3 3
15:00 10 31 10 3 53 3 3 3 5 3
20:00 20 33 33 3 86 3 3 21 3 3
23:00 31 34 45 63 43 12 1 0 2 5

I want to get a new DataFrame containing the arithmetic mean of each row, for each column containing a date. Example:

Hours avg_count
00:00 4.7
05:00 6.7
10:00 10
15:00 12.4
20:00 20.8
23:00 23.6

Finally I want to round to an integer value:

Hours avg_count
00:00 5
05:00 7
10:00 10
15:00 12
20:00 21
23:00 24

CodePudding user response:

Use:

df1 = df.set_index('Hour').mean(axis=1).round(0).astype(int).reset_index(name='avg_count')
  • Related