Converting Values to NaNs in All Columns

Python

Example of how to impute data in all columns. In this example we are replacing any values that are question marks to NaNs.

 1|  import pandas as pd
 2|  import numpy as np
 3|  
 4|  #If value in dataframe is ? then return NaN, otherwise return the value unchanged.
 5|  def impute_data(x):
 6|      if x == "?":
 7|          return np.NaN
 8|      else:
 9|          return x
10|  
11|  for col, content in data.items():
12|      data[col] = data[col].apply(impute_data)
Did you find this snippet useful?

Sign up for free to to add this to your code library