Fill NaNs in pandas columns using mean for numeric dtype, mode for non-numeric dtype

Viewed 1048
    # handling missing values
    class handling_missing_data():
    
      # Imputation
      # Handling columns which have null values
      
      for col in df[:]:
        if ():
    
          if (pd.df[:].astype(pd.Series([np.integer]))):
    
            df = df.select_dtypes(include=[np.integer]).fillna(df.select_dtypes(include=[np.integer]).mean().iloc[0], inplace=True)
      
          elif (pd.df[:].astype(pd.Series([object, str]))):
            
            df = df.select_dtypes(include=['object', 'str']).fillna(df.select_dtypes(include=['object', 'str']).mode().iloc[0], inplace=True)
      
      print(df.head())

Why this code is not working as I am trying to identify missing values in dataset in a particular column and fill the missing column values with mean, mode based on column datatype via using loop. I am looking for some generalized methods.

1 Answers

There is too much wrong with your code to reasonably go over in an answer, so let me just show you how I'd do it instead.

# Select numeric columns.
a = df.select_dtypes('number')
# Select string and object columns.
b = df.select_dtypes('object')

# Fill numeric columns with mean.
df[a.columns] = a.fillna(a.mean())
# Fill object columns with mode.
df[b.columns] = b.fillna(b.agg(lambda x: x.mode().values[0])
Related