1

for example, suppose I have a dataframe which is like,

enter code here
df = pd.DataFrame([[1,      np.nan, 2],
                   [2,      3,      5],
                   [np.nan, 4,      6],
                   [None, 4,      6]])

however, how can I fill the NaN in this dataframe with the average value of the row that NaN belongs to? The result of this dataframe should be

enter code here
     0     1    2
0  1.0   1.5  2.0
1  2.0   3.0  5.0
2  5.0   4.0  6.0
3  5.0   4.0  6.0
Mohsen
  • 1,079
  • 2
  • 8
  • 23
Johnny
  • 13
  • 4
  • Does this answer your question? [Creating an empty Pandas DataFrame, then filling it?](https://stackoverflow.com/questions/13784192/creating-an-empty-pandas-dataframe-then-filling-it) – EnriqueBet Mar 26 '20 at 15:58
  • No, I just want to know how to get the results of the following sample using pandas library functions. – Johnny Mar 26 '20 at 16:00

1 Answers1

0
df = pd.DataFrame([[1,      np.nan, 2],
                   [2,      3,      5],
                   [np.nan, 4,      6],
                   [None, 4,      6]])

df.mean()

0    1.500000
1    3.666667
2    4.750000
dtype: float64

df.fillna(df.mean(), inplace=True)


df
     0       1        2
0   1.0   3.666667    2
1   2.0   3.000000    5
2   1.5   4.000000    6
3   1.5   4.000000    6
JA-pythonista
  • 1,225
  • 1
  • 21
  • 44