If I try:
ints = np.arange(10)
ints[0] = np.nan
I get the following error:
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot convert float NaN to integer
Is there a workaround here? The solution I have so far is to convert the array to dtype=float like so:
casted = np.array(ints,dtype=float)
casted[0] = np.nan # no errors
-
Integer types don't have a "NaN" value, only floating-point types do. The best way to solve your problem depends on what your problem actually is, which is to say, on why you want to store "NaN" values in the array.Karl Knechtel– Karl Knechtel2020年07月01日 08:06:24 +00:00Commented Jul 1, 2020 at 8:06
-
Does the given answer solve your requirement now?JALO - JusAnotherLivngOrganism– JALO - JusAnotherLivngOrganism2020年07月01日 09:00:13 +00:00Commented Jul 1, 2020 at 9:00
2 Answers 2
import pandas as pd
import numpy as np
If a NAN array is needed then:
array = np.empty(3)
array[:] = np.NaN
or if you need to change a given value then:
ints = np.arange(10).astype(float)
ints[0]=np.NAN
pdintseries=pd.Series(int).astype(dtype='Int64') #pandas has released support for nan containing Int64 dtypes.
You can further convert the series to numpy object.
or directly:
int=np.arange(10).astype(object)
int[0]=np.NAN
Doesn't specifically solve your problem, but some way out here.
Comments
I dont know what you actual problem is but I has a simlar issue where I wanted to set a value to NaN if the value was an "error mesurement". What I instead did was to generate a "Correct index" list where all of the non-error elements where indicated with respective index:
# A sensor could measure distance and angle
non_error = np.where(distance != 4294967295) # 4294967295 indicates an error
non_error_angle = angle[non_error]
non_error_distance = distance[non_error]
In the actual implementation I had multiple arrays of data that all had the same error index so the non_error list could be used to find the non-error elements in all of the arrays without any risk of messing up the order of the data since they corresponded with index.