Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace None with NaN in pandas dataframe

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?

like image 672
AdamNYC Avatar asked Sep 28 '22 10:09

AdamNYC


People also ask

How do I replace None with NA in Python?

Use DataFrame. fillna or Series. fillna which will help in replacing the Python object None, not the string 'None'.

Is None same as NaN in Pandas?

In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN : NaN (an acronym for Not a Number), is a special floating-point value recognized by all systems that use the standard IEEE floating-point representation.


2 Answers

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)
like image 221
Guillaume Jacquenot Avatar answered Oct 20 '22 23:10

Guillaume Jacquenot


Here's another option:

df.replace(to_replace=[None], value=np.nan, inplace=True)
like image 25
Nickolai Avatar answered Oct 21 '22 00:10

Nickolai