Reputation: 51
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:
np.isnan(array).all()
Is there a way for type Decimal
?
The solution would be better without iteration.
Upvotes: 1
Views: 996
Reputation: 13743
You could use NumPy's vectorize
to avoid iteration.
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
. Notice that you need to convert that list into a NumPy array.
Upvotes: 1
Reputation: 9721
From my comment above, I realise it’s an iteration. The reason is that np.isnan
does not support Decimal
as an input type; 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.
Additionally, as commented by @juanpa.arrivillaga, as the Decimal
objects are in a list
, iteration is the only way. Numpy is not necessary in this operation.
One method is:
all([i.is_nan() for i in array])
Upvotes: 0