QNA > H > How To Replace All Blank/Empty Cells In A Pandas Dataframe With Nans

How to replace all blank/empty cells in a pandas dataframe with NaNs

As has already been mentioned, the best way to accomplish this is to use df.replace().

  1. >>> import pandas as pd 
  2. >>> import numpy as np 
  3. >>> df = pd.DataFrame({'A':[1, 2, '', 4, ''], 'B':[6, 7, '', '', 10]}) 
  4. >>> df 
  5. A B 
  6. 0 1 6 
  7. 1 2 7 
  8. 2  
  9. 3 4  
  10. 4 10 
  11.  
  12. >>> df.replace('', np.nan) 
  13. A B 
  14. 0 1.0 6.0 
  15. 1 2.0 7.0 
  16. 2 NaN NaN 
  17. 3 4.0 NaN 
  18. 4 NaN 10.0 

You can either use this to create a new DataFrame or use inplace = True to apply it to your current DataFrame object.

This also works with columns. If, for example, you only wanted to replace all of the blanks in column A while leaving the blanks in column B, then you could use df.A.replace().

  1. >>> df.A.replace('', np.nan, inplace = True) 
  2. >>> df 
  3. A B 
  4. 0 1.0 6 
  5. 1 2.0 7 
  6. 2 NaN  
  7. 3 4.0  
  8. 4 NaN 10 

Di Vincent

Di quale hardware del server ho bisogno per un gioco come Clash of Clans? :: Si possono scaricare giochi come CoC?
Link utili