2

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

1 Answer 1

2

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', '--', '--', '--', '--']
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. That works, but I need to intersperse ' &' elements for a Latex table, and that adds complexity.
@dcnicholls I change it to save to a list, it's longer than your code but this seems like a job for masked array
That's a nice one-liner. Thanks
You can also just use np.ma.fix_invalid.
@tiago that's much better, updated and community wikied since that's a much better way of doing it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.