0

I have a multi-indexed pivot table, lets say its about temperature, and it looks like the following:

days    1.      2.      3.      4.      5.      6.      7.   
city
miami  NaN     NaN     NaN      11     NaN      45     54
tampa  NaN     NaN     NaN      36     NaN     NaN     54

I want to create an average column that adds the non-NaN columns and divides them by the number of non-NaN columns. It would look like below.

days     1.     2.      3.      4.      5.      6.      7.avg_num
city
maimi   NaN    NaN     NaN      11     NaN      45     54     36  
tampa   NaN    NaN     NaN      36     NaN     NaN     54     45

Perhaps a loc indexing with add method? Help is greatly appreciated, thanks.

Digital Moniker
  • 281
  • 1
  • 12
  • 2
    Do you mean `df['avg_num'] = df.mean(axis=1)`? Your current output is the row sums (`df['avg_num'] = df.sum(axis=1)`) which is misleading. – Henry Ecker Nov 06 '21 at 19:35
  • Yeah, thanks I was overcomplicating things! – Digital Moniker Nov 06 '21 at 19:41
  • 1
    Np. Most mathematical operations in pandas exclude `NaN` by default. (Since including them will result in `NaN`s) So this is more straightforward than would be normally expected. – Henry Ecker Nov 06 '21 at 19:45

0 Answers0