[英]how do I check decimal.is_nan() for all values in array?
Suppose I have my array like this:假设我有这样的数组:
from decimal import Decimal
array = [Decimal(np.nan), Decimal(np.nan), Decimal(0.231411)]
I know that if the types are float
, I can check if all the values are nan
or not , as:我知道如果类型是float
,我可以检查所有值是否都是nan
,如:
np.isnan(array).all()
Is there a way for type Decimal
?有没有办法输入Decimal
类型?
The solution would be better without iteration.如果没有迭代,解决方案会更好。
You could use NumPy's vectorize
to avoid iteration.您可以使用 NumPy 的vectorize
来避免迭代。
In [40]: from decimal import Decimal
In [41]: import numpy as np
In [42]: nums = [Decimal(np.nan), Decimal(np.nan), Decimal(0.231411)]
In [43]: nums
Out[43]:
[Decimal('NaN'),
Decimal('NaN'),
Decimal('0.2314110000000000055830895462349872104823589324951171875')]
In [44]: np.all(np.vectorize(lambda x: x.is_nan())(np.asarray(nums)))
Out[44]: False
In [45]: np.all(np.vectorize(lambda x: x.is_nan())(np.asarray(nums[:-1])))
Out[45]: True
In the snippet above nums
is a list of instances of class Decimal
.在上面的nums
片段中,是类Decimal
的实例列表。 Notice that you need to convert that list into a NumPy array.请注意,您需要将该列表转换为 NumPy 数组。
From my comment above, I realise it's an iteration.从我上面的评论中,我意识到这是一个迭代。 The reason is that np.isnan
does not support Decimal
as an input type;原因是np.isnan
不支持Decimal
作为输入类型; therefore, I don't believe this can be done via broadcasting, without converting the datatype - which means a potential precision loss, which is a reason to use a Decimal
type.因此,我不相信这可以通过广播来完成,而不转换数据类型 - 这意味着潜在的精度损失,这是使用Decimal
类型的原因。
Additionally, as commented by @juanpa.arrivillaga, as the Decimal
objects are in a list
, iteration is the only way.此外,正如@juanpa.arrivillaga 所评论的,由于Decimal
对象在list
,迭代是唯一的方法。 Numpy is not necessary in this operation.此操作中不需要 Numpy。
One method is:一种方法是:
all([i.is_nan() for i in array])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.