meerkat
meerkat

Reputation: 1122

Changning value of int array to NaN in Python (ValueError)

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 

Upvotes: 0

Views: 40

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.

na support pd series

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.

Upvotes: 1

JakobVinkas
JakobVinkas

Reputation: 1063

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.

Upvotes: 1

Related Questions