0

I read data from csv and fillna with mode like this code.

df = pd.read_csv(r'C:\\Users\PC\Downloads\File.csv')
df.fillna(df.mode(), inplace=True)

It still show NaN value like this.

0          0.0     0.0      4.7       0.0     138.0       0.15       0.15   
1          0.0     1.0      3.5       0.0     132.0       0.38       0.18   
2          0.0     0.0      4.0       0.0     132.0       0.30       0.11   
3          0.0     1.0      3.9       0.0     146.0       0.75       0.37   
4          0.0     1.0      3.5       0.0     132.0       0.45       0.22   
5          0.0     NaN      NaN       NaN       NaN       0.45       0.22   
6          0.0     NaN      NaN       NaN       NaN       0.30       0.11   
7          0.0     0.0      4.5       0.0     136.0        NaN        NaN   
8          0.0     NaN      NaN       NaN       NaN       0.30       0.37   
9          0.0     NaN      NaN       NaN       NaN       0.38       0.11  

If I fillna with mean it have no problem. How to fillna with mode?

user572575
  • 1,009
  • 3
  • 25
  • 45

1 Answers1

1

Because DataFrame.mode should return multiple values if smae number of maximum counts, select first row:

print (df.mode())
     1    2    3    4      5    6     7
0  0.0  0.0  3.5  0.0  132.0  0.3  0.11
1  NaN  1.0  NaN  NaN    NaN  NaN   NaN

df.fillna(df.mode().iloc[0], inplace=True)
print (df)
     1    2    3    4      5     6     7
0                                       
0  0.0  0.0  4.7  0.0  138.0  0.15  0.15
1  0.0  1.0  3.5  0.0  132.0  0.38  0.18
2  0.0  0.0  4.0  0.0  132.0  0.30  0.11
3  0.0  1.0  3.9  0.0  146.0  0.75  0.37
4  0.0  1.0  3.5  0.0  132.0  0.45  0.22
5  0.0  0.0  3.5  0.0  132.0  0.45  0.22
6  0.0  0.0  3.5  0.0  132.0  0.30  0.11
7  0.0  0.0  4.5  0.0  136.0  0.30  0.11
8  0.0  0.0  3.5  0.0  132.0  0.30  0.37
9  0.0  0.0  3.5  0.0  132.0  0.38  0.11
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252