不在 matplotlib 中绘制“零”或将零更改为无 [Python]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18697417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:30:54  来源:igfitidea点击:

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

pythonnumpymatplotlibzero

提问by Ashleigh Clayton

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

我有下面的代码,我想将数据中的所有零转换为None's (因为我不想在 matplotlib 中绘制数据)。但是,代码不起作用并且0.仍在打印

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.

任何人都可以想到解决这个问题的方法。或者只是我如何将所有 0 转移到None. 或者只是不在 Matplotlib 中绘制零值。

采纳答案by tamasgal

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

使用 numpy 当然是更好的选择,除非您有充分的理由不使用它;) 为此,请参阅 Daniel 的回答。

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

如果你想要一个裸 Python 解决方案,你可以这样做:

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.

Matplotlib 不会绘制nan(不是数字)值。

回答by Daniel

Why not use numpy for this?

为什么不为此使用 numpy?

>>> 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.

需要注意的是,values 不能是整数类型的数组。