How to replace NA values ​​with DataFrame column mode in python?

I am completely new to Python (and this website), and I'm currently trying to replace the NA values ​​in certain columns of data frames with my mode. I tried various methods that do not work. Please help me determine what I am doing wrong:

Note. All the columns I'm working with are types float64. All my codes run, but when I check the zero count with df[cols_mode].isnull().sum()in the columns, it remains the same.

Method 1:

cols_mode = ['race', 'goal', 'date', 'go_out', 'career_c']

df[cols_mode].apply(lambda x: x.fillna(x.mode, inplace=True))

I also tried using the Imputer method, but came across the same result

Method 2:

for column in df[['race', 'goal', 'date', 'go_out', 'career_c']]:
    mode = df[column].mode()
    df[column] = df[column].fillna(mode)

Method 3:

df['race'].fillna(df.race.mode(), inplace=True)
df['goal'].fillna(df.goal.mode(), inplace=True)
df['date'].fillna(df.date.mode(), inplace=True)
df['go_out'].fillna(df.go_out.mode(), inplace=True)
df['career_c'].fillna(df.career_c.mode(), inplace=True)

Method 4: My methods are becoming an increasingly manual process, and finally this works:

df['race'].fillna(2.0, inplace=True)
df['goal'].fillna(1.0, inplace=True)
df['date'].fillna(6.0, inplace=True)
df['go_out'].fillna(2.0, inplace=True)
df['career_c'].fillna(2.0, inplace=True) 
+4
1

mode , , , NaN DataFrame.

for column in ['race', 'goal', 'date', 'go_out', 'career_c']:
    df[column].fillna(df[column].mode()[0], inplace=True)

DataFrame, :

for column in df.columns:
    df[column].fillna(df[column].mode()[0], inplace=True)
+2

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


All Articles