Zanam
Zanam

Reputation: 4807

Pandas pivot table ignoring zeros while taking mean

I am trying the following

import pandas as pd
import numpy as np

dfout3 = pd.DataFrame({'Idx': MnthIdx,
                       'Col1': Val1,
                       'Col2': Val2,
                       'Col3': Val3)})

MeanTable1 = pd.pivot_table(dfout3, index=['Idx'], values=['Col1','Col2','Col3'], aggfunc=[np.mean])

But I would like to ignore zeros's while taking the mean for each of values. Is there way through pandas instead of me doing index for zeros and getting rid of them and taking mean of columns?

Upvotes: 0

Views: 1274

Answers (2)

n.r.
n.r.

Reputation: 919

While @ysearka's answer points into the right direction, it's not working (anymore?):

This is how the loop works for me:

for col in dfout3.columns:
   dfout3.loc[dfout3[col] == 0] = dfout3[col]mean()

Upvotes: 1

ysearka
ysearka

Reputation: 3855

I don't know if there is a way to ignore zeros, but you can set them as the mean value before the pivot (which will give the same result):

for col in dfout3.columns:
    dfout3.ix[dfout3.col == 0,col] = dfout3.col.mean()

Upvotes: 1

Related Questions