Not plotting 'zero' in matplotlib or change zero to None [Python]

Using numpy is of course the better choice, unless you have any good reasons not to use it ;) For that, see Daniel's answer.

If you want to have a bare Python solution, you might do something like this:

values = [3, 5, 0, 3, 5, 1, 4, 0, 9]

def zero_to_nan(values):
    """Replace every 0 with 'nan' and return a copy."""
    return [float('nan') if x==0 else x for x in values]

print(zero_to_nan(values))

gives you:

[3, 5, nan, 3, 5, 1, 4, nan, 9]

Matplotlib won't plot nan (not a number) values.


Why not use numpy for this?

>>> values = np.array([3, 5, 0, 3, 5, 1, 4, 0, 9], dtype=np.double)
>>> values[ values==0 ] = np.nan
>>> values
array([  3.,   5.,  nan,   3.,   5.,   1.,   4.,  nan,   9.])

It should be noted that values cannot be an integer type array.