Reputation: 10443
I have the following data frame:
From which a want to get the average row-wise of non zero columns.
E.G. for
row 0: (1303 + 1316 + 1322 + 1315)/4
row 2: (1632 + 1628 + 1609)/3
Upvotes: 0
Views: 38
Reputation: 863751
Use sum
twice - all values by sum of True
s processes like 1
:
df = df.sum(axis=1).div(df.ne(0).sum(1))
Timings:
np.random.seed(1997)
df = pd.DataFrame(np.random.randint(3, size=(1000,1000)))
#print (df)
In [60]: %timeit (df.replace(0,np.nan).mean(1))
1 loop, best of 3: 188 ms per loop
In [61]: %timeit (df.sum(axis=1).div(df.ne(0).sum(1)))
10 loops, best of 3: 21.8 ms per loop
Upvotes: 0