Replace None with NaN in pandas dataframe

AdamNYC picture AdamNYC · May 19, 2014 · Viewed 123.2k times · Source

I have table x:

        website
0   http://www.google.com/
1   http://www.yahoo.com
2   None

I want to replace python None with pandas NaN. I tried:

x.replace(to_replace=None, value=np.nan)

But I got:

TypeError: 'regex' must be a string or a compiled regular expression or a list or dict of strings or regular expressions, you passed a 'bool'

How should I go about it?

Answer

Guillaume Jacquenot picture Guillaume Jacquenot · May 19, 2014

You can use DataFrame.fillna or Series.fillna which will replace the Python object None, not the string 'None'.

import pandas as pd
import numpy as np

For dataframe:

df = df.fillna(value=np.nan)

For column or series:

df.mycol.fillna(value=np.nan, inplace=True)