how to replace NaN value in python

14,712

Solution 1

Use fillna (docs): An example -

df = pd.DataFrame({'no': [1, 2, 3],
                    'Col1':['State','City','Town'],
                  'Col2':['abc', np.NaN, 'defg'],
                  'Col3':['Madhya Pradesh', 'VBI', 'KJI']})

df

   no   Col1    Col2    Col3
0   1   State   abc Madhya Pradesh
1   2   City    NaN VBI
2   3   Town    defg    KJI

df.Col2.fillna('', inplace=True)
df

    no  Col1    Col2    Col3
0   1   State   abc     Madhya Pradesh
1   2   City            VBI
2   3   Town    defg    KJI

Solution 2

Simple! you can do this way

df_conbid_N_1 = pd.read_csv("test-2019.csv",dtype=str, sep=';',encoding='utf-8').fillna("")
Share:
14,712
yatu
Author by

yatu

Latest blog post 🡳 Building a memory based collaborative filtering recommender Hi there! I'm Àlex, a data scientist from Barcelona with an engineering background. Since my graduate degree I've been mainly focusing in machine learning. Currently most of my time at work is split between developing in python and ML related projects. I'm here to improve my python skills, and help anyone I can along the way! 285th awardee of the Legendary badge Couple of decent-ish answers: LabelEncoder for categorical features? Combine lists with common elements NumPy/Numba speedups How to change the colour of an image using a mask? How to create random graph where each node has at least 1 edge using Networkx

Updated on June 04, 2022

Comments

  • yatu
    yatu almost 2 years

    I have a list of NaN values in my dataframe and I want to replace NaN values with an empty string.

    What I've tried so far, which isn't working:

    df_conbid_N_1 = pd.read_csv("test-2019.csv",dtype=str, sep=';', encoding='utf-8')
    df_conbid_N_1['Excep_Test'] = df_conbid_N_1['Excep_Test'].replace("NaN","")