Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
up vote 2 down vote accepted

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', '--', '--', '--', '--']
share|improve this answer
    
Thanks. That works, but I need to intersperse ' &' elements for a Latex table, and that adds complexity. – dcnicholls Jun 8 '13 at 6:03
    
@dcnicholls I change it to save to a list, it's longer than your code but this seems like a job for masked array – jamylak Jun 8 '13 at 6:09
    
That's a nice one-liner. Thanks – dcnicholls Jun 8 '13 at 6:14
    
You can also just use np.ma.fix_invalid. – tiago Jun 8 '13 at 7:07
    
@tiago that's much better, updated and community wikied since that's a much better way of doing it – jamylak Jun 8 '13 at 8:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.