Computing averages of multiple columns ignoring NaN pandas numpy

I have a base table of values:

import pandas as pd
import numpy as np
test = pd.read_csv('mean_test.csv')
test.replace('n/a',np.nan)
test


value1  value2  value3
1   9   5
5   NaN 4
9   55  NaN
NaN 4   9

I want to work out an average of three values, ignoring NaN, so for the second line it will be (5 + 4) / 2. Therefore, I cannot use the .replace function to put a zero in the NaN place. I looked through some other questions, but cannot find anything to cover it. Am I missing something?

+4
source share
1 answer

Pandas takes care of NaNfor you:

>>> df
value1  value2  value3
0       1       9       5
1       5     NaN       4
2       9      55     NaN
3     NaN       4       9

>>> df.mean(axis=1)
0     5.0
1     4.5
2    32.0
3     6.5
dtype: float64
+5
source

Source: https://habr.com/ru/post/1621876/


All Articles