python - Replace Numpy NaN with string in list with strings -
i have list containing string elements, , several nan numpy floats. e.g.
l=['foo', 'bar', 'baz', 'nan']
how replace float nan
string missing
?
most answers found regard issue in pandas dataframe.
try 1:
for x in l: x=x.replace('nan', 'missing')
gives attributeerror: 'float' object has no attribute 'replace'
try 2:
for x in l: if str(x)=='nan': x=str(x)
command executes, nothing changes.
advised comments:
['missing' if x 'nan' else x x in l]
['missing' if x np.isnan else x x in l]
['missing' if x np.nan else x x in l]
commands execute, nothing changes.
i think have bad format nan's (notice nan outputed nan , not 'nan'). answers comment should work:
>>> import numpy np >>> l=['foo', 'bar', 'baz', np.nan] >>> print l ['foo', 'bar', 'baz', nan] >>> l_new=['missing' if x np.nan else x x in l] >>> print l_new ['foo', 'bar', 'baz', 'missing']
for current problem maybe make following solution:
my_nan=l['some_index_with_nan'] l_new=['missing' if x my_nan else x x in l]
Comments
Post a Comment