Python中将int数组的值更改为NaN(ValueError)

Python中将int数组的值更改为NaN(ValueError),python,numpy,nan,Python,Numpy,Nan,如果我尝试: ints = np.arange(10) ints[0] = np.nan 我得到以下错误: Error: Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot convert float NaN to integer 我不知道您的实际问题是什么,但我有一个类似的问题,我想将值设置为NaN,如果该值是“误差

如果我尝试:

ints = np.arange(10)
ints[0] = np.nan
我得到以下错误:

Error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot convert float NaN to integer

我不知道您的实际问题是什么,但我有一个类似的问题,我想将值设置为
NaN
,如果该值是“误差测量”。我所做的是生成一个“正确索引”列表,其中所有非错误元素都用各自的索引表示:

# 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]

在实际的实现中,我有多个数据数组,所有数组都有相同的错误索引,因此可以使用
非错误
列表来查找所有数组中的非错误元素,而不会有弄乱数据顺序的风险,因为它们与索引相对应。

我不知道您实际的问题是什么,但我有一个简单的问题如果值是“误差测量”,我想将值设置为
NaN
。我所做的是生成一个“正确索引”列表,其中所有非错误元素都用各自的索引表示:

# 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]
import pandas as pd
import numpy as np
在实际的实现中,我有多个数据数组,所有数组都有相同的错误索引,因此
non_error
列表可以用于查找所有数组中的非错误元素,而不会有弄乱数据顺序的风险,因为它们与索引对应

import pandas as pd
import numpy as np
如果需要NAN阵列,则:

array = np.empty(3)
array[:] = np.NaN
或者,如果需要更改给定值,则:

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.

可以进一步将序列转换为numpy对象

或直接:

int=np.arange(10).astype(object)
int[0]=np.NAN
并没有特别解决你的问题,但有办法解决

如果需要NAN阵列,则:

array = np.empty(3)
array[:] = np.NaN
或者,如果需要更改给定值,则:

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.

可以进一步将序列转换为numpy对象

或直接:

int=np.arange(10).astype(object)
int[0]=np.NAN

没有专门解决您的问题,但有办法解决。

整数类型没有“NaN”值,只有浮点类型有。解决问题的最佳方法取决于实际问题是什么,也就是说,取决于为什么要在数组中存储“NaN”值。给定的答案现在能满足您的要求吗?整数类型没有“NaN”值,只有浮点类型有。解决问题的最佳方法取决于实际问题是什么,也就是说,取决于为什么要在数组中存储“NaN”值。给出的答案现在能满足您的要求吗?