Nan fill-list values

How to fill nan values ​​with 0 in a list. I can do this for dataframes but don't know how to do it for lists?

listname=listname.fillna(0)

      

This does not work.

+3


source to share


3 answers


You can convert to pandas series and return to list

pd.Series(listname).fillna(0).tolist()

      

Consider the list listname



listname = [1, np.nan, 2, None, 3]

      

Then

pd.Series(listname, dtype=object).fillna(0).tolist()

[1, 0, 2, 0, 3]

      

+1


source


listname1=listname.fillna()

      



this will work for all int, string, float values

+1


source


You can use a list comprehension and check with math.isnan :

import math
listname = [0 if math.isnan(x) else x for x in listname]

      

But that won't work with non float types, if your list has strings, other numeric types, etc., then you can use str(x) != 'nan

'

listname = [0 if str(x)=='nan' else x for x in listname]

      

0


source







All Articles