Reputation: 391
I have a numpy array with some floats and some nans:
a = [ 8.08970226 nan nan 8.30043545 nan nan nan nan]
I want to convert it to an array (for printing in Latex) to the mixed form:
a = ['8.08970226', '--', '--', '8.30043545', '--', '--', '--', '--']
The method I've worked out, which is not elegant, is:
a=a.astype('|S10')
a[a=='nan']='--'
a=list(a)
Is there a more elegant way to do the job? (I could probably stop at the second line for my Latex requirement.)
Advice apreciated
Upvotes: 2
Views: 220
Reputation: 133574
Using numpy
masked arrays
>>> import numpy as np
>>> a = np.array([ 8.08970226, np.NAN, np.NAN, 8.30043545, np.NAN, np.NAN, np.NAN, np.NAN])
>>> np.ma.fix_invalid(a)
masked_array(data = [8.08970226 -- -- 8.30043545 -- -- -- --],
mask = [False True True False True True True True],
fill_value = 1e+20)
>>> print _
[8.08970226 -- -- 8.30043545 -- -- -- --]
or since you need it as that particular list:
>>> np.ma.fix_invalid(a).astype('|S10').tolist(fill_value='--')
['8.08970226', '--', '--', '8.30043545', '--', '--', '--', '--']
Upvotes: 2