Issue
I have a list containing string elements, and several NaN numpy floats. E.g.
l=['foo', 'bar', 'baz', 'nan']
How do I replace the float nan
to the string missing
?
Most answers I found regard this issue in a 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, but nothing changes.
Advised by comments:
['missing' if x is 'nan' else x for x in l]
['missing' if x is np.isnan else x for x in l]
['missing' if x is np.nan else x for x in l]
Commands execute, but nothing changes.
Solution
I think you have a bad format for your NaN's (notice the nan is outputed nan and not 'nan'). The answers from the comment should work:
>>> import numpy as np
>>> l=['foo', 'bar', 'baz', np.nan]
>>> print l
['foo', 'bar', 'baz', nan]
>>> l_new=['missing' if x is np.nan else x for x in l]
>>> print l_new
['foo', 'bar', 'baz', 'missing']
For your current problem maybe make the following solution:
my_nan=l['some_index_with_nan']
l_new=['missing' if x is my_nan else x for x in l]
Answered By - Peter Mølgaard Pallesen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.