Search code examples
pythonpandasdata-analysis

How to assign value to NaN in pandas series?


import pandas as pd
import numpy as np    

data = {'a' : 0., 'b' : 1., 'c' : 2.}

s = pd.Series(data,index=['b','c','d','a'])
print (s)

OUTPUT IS : 

b    1.0
c    2.0
d    NaN
a    0.0
dtype: float64

I want to assign some values to NaN. Finally i got the answer. I was thinking to remove the nan with empty string "" and below is the code.

        data = pd.read_excel(i)
        data1 = data.replace(np.nan, '', regex=True)
        data1.columns = data1.columns.str.replace('Unnamed.*', '')

Solution

  • You can use fillna method of pandas.

    s.fillna(0)
    

    You can also replace with mean or median of Series

    s.fillna(s.median()) 
    
    #or
    
    s.fillna(s.mean())