是什么原因,为什么我的numpy数组的最大和最小值是nan?我检查了我的数组:
for i in range(data[0]):
if data[i] == numpy.nan:
print("nan")
我的数据里没有南。我的搜索错了吗?如果不是:麦克斯和敏成为南的原因是什么?
发布于 2020-07-12 11:41:55
给你:
import numpy as np
a = np.array([1, 2, 3, np.nan, 4])
print(f'a.max() = {a.max()}')
print(f'np.nanmax(a) = {np.nanmax(a)}')
print(f'a.min() = {a.min()}')
print(f'np.nanmin(a) = {np.nanmin(a)}')
输出:
a.max() = nan
np.nanmax(a) = 4.0
a.min() = nan
np.nanmin(a) = 1.0
发布于 2020-07-12 12:24:21
Balaji精确地展示了如何找到min / max,即使源数组包含NaN,在这个问题上也没有什么可添加的。
但是,您的代码示例还包含值得指出的其他缺陷。
for i in range(data[0]):
。您可能希望为数据的每个元素执行这个循环,但是您的循环将被执行的次数与数据的初始元素的值一样多。
变体:- If it is e.g. _1_, it will be executed only once.
- If it is _0_ or negative, it will not be executed at all.
- If it is >= than the size of _data_, _IndexError_ exception will be raised.
- If your array contains at least 1 _NaN_, then the whole array is of _float_ type (_NaN_ is a special case of _float_) and you get _TypeError_ exception: _'numpy.float64' object cannot be interpreted as an integer_.
Remedium (可能的变体之一):这个循环应该从for elem in data:
开始,内部的代码应该使用elem作为当前的数据元素。
if data[i] == numpy.nan:
。即使您将其更正为if elem == np.nan:
,if块中的代码也不会执行。原因是,根据定义,np.nan是而不是等于任何其他值,即使这个其他值是另一个np.nan。
Remedium:改为if np.isnan(elem):(Balaji在他的评论how to Change 中写道,我添加了为什么是)。最后:如何快速检查数组中的_NaN_s:
np.isnan(data)
,您将得到一个bool数组。np.isnan(data).any()
。这段代码更短,运行速度也更快。
发布于 2020-07-12 12:31:32
原因是np.nan == x
总是假的,即使x是np.nan
。这与NaN在维基百科中的定义是一致的。
检查你自己:
In [4]: import numpy as np
In [5]: np.nan == np.nan
Out[5]: False
如果要检查数字x
是否为np.nan
,则必须使用
np.isnan(x)
如果您想要获得最大/分钟的np.array和nan,请使用np.nanmax()
/ np.nanmin()
minval = np.nanmin(data)
https://stackoverflow.com/questions/62865647
复制