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

时光怂恿深爱的人放手 提交于 2019-12-17 20:44:22

问题


I have the code below and I would like to convert all zero's in the data to None's (as I do not want to plot the data here in matplotlib). However, the code is notworking and 0. is still being printed

sd_rel_track_sum=np.sum(sd_rel_track, axis=1)
for i in sd_rel_track_sum:
   print i
   if i==0:
       i=None

return sd_rel_track_sum

Can anyone think of a solution to this. Or just an answer for how I can transfer all 0 to None. Or just not plot the zero values in Matplotlib.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18697417/not-plotting-zero-in-matplotlib-or-change-zero-to-none-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!