Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Asked on December 24, 2018 in Pandas.
Add Comment


  • 2 Answer(s)

    Refer indexing before going to the solution:

    df1 = df.where((pd.notnull(df)), None)
    

    It is to be noted that the above code changes the dtype of all columns to object:

    n [1]: df = pd.DataFrame([1, np.nan])
     
    In [2]: df
    Out[2]:
    0
    0 1
    1 NaN
     
    In [3]: df1 = df.where((pd.notnull(df)), None)
     
    In [4]: df1
    Out[4]:
    0
    0 1
    1 None
    

    Refer to the astypefunction fillna.

    df1 = df.astype(object).replace(np.nan, 'None')
    

    The function replace does not work None. Refer to the issue here.

    Answered on December 24, 2018.
    Add Comment

    One can also use the below one liner:

    df = df.astype(object).where(pd.notnull(df),None)
    
    Answered on December 24, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.