当numpy dtype为“ object”时,将nan转换为零

时间:2019-09-09 07:20:57

标签: python numpy nan dtype

我有一个包含nan的numpy数组。我尝试使用

将这些nans转换为零
 X_ = np.nan_to_num(X_, copy = False)

但是没有用。我怀疑它是因为X_的dtype是对象。我尝试使用

将其转换为float64
X_= X_.astype(np.float64)

但是那也不起作用

当dtype是object时,是否可以将nan转换为零?

4 个答案:

答案 0 :(得分:0)

a  = [np.nan]
b = np.array(a)
c = np.nan_to_num(b)
print(b)
print(c)

结果:

[nan]
[0.]

有效。检查您的X_格式。

答案 1 :(得分:0)

似乎由于对象类型的原因,无法转换为float。可能有点hacky,但是您可以尝试转换为str:

void Start()
{
    cameraContainer = new GameObject("Camera Container");
    cameraContainer.transform.position = transform.position;
    transform.SetParent(cameraContainer.transform);

    gyroEnabled = EnableGyro();
}

// Update is called once per frame
void Update()
{
    if(gyroEnabled)
    {
        transform.localRotation = gyro.attitude * rot;
    }
}

private bool EnableGyro()
{
    if(SystemInfo.supportsGyroscope)
    {
        gyro = Input.gyro;
        gyro.enabled = true;

        cameraContainer.transform.rotation = Quaternion.Euler(90f, 90f, 0);
        rot = new Quaternion(0, 0, 1, 0);

        return true;
    }

    return false;
}

答案 2 :(得分:0)

如果您的数组仅包含“合理”(请参见下文)元素,则可以使用以下解决方法:

np.where(X_==X_,X_,0)

在合理的范围内,我的意思是元素e满足e == e,唯一例外是nan。例如,如果没有将用户定义的类用作元素,则应该是这种情况。

答案 3 :(得分:0)

“ object” dtype也引起了我一个问题。但是您的astype(np.float64)确实为我工作。谢谢!

print("Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:")
A = np.array([1., 2., 3., np.nan]); print('A:', A, A.dtype)
B = pd.DataFrame([[1., 2., 3., np.nan,],  [1, 2, 3, '4']]
                  ).to_numpy();  print('B:', B, B.dtype, '\n')

print('Converting vanilla A is fine:\n', np.nan_to_num(A, nan=-99), '\n')
print('But not B:\n', np.nan_to_num(B, nan=-99), '\n')
print('Not even this slice of B, \nB[0, :] : ', B[0, :])
print(np.nan_to_num(B[0, :], nan=-99), '\n')

print('The astype(np.float64) does the trick here:\n', 
      np.nan_to_num(B[0, :].astype(np.float64), nan=-99), '\n\n')

输出:

Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:
A: [ 1.  2.  3. nan] float64
B: [[1.0 2.0 3.0 nan]
 [1.0 2.0 3.0 '4']] object 

Converting vanilla A is fine:
 [  1.   2.   3. -99.] 

But not B:
 [[1.0 2.0 3.0 nan]
 [1.0 2.0 3.0 '4']] 

Not even this slice of B, 
B[0, :] :  [1.0 2.0 3.0 nan]
[1.0 2.0 3.0 nan] 

The astype(np.float64) does the trick here:
 [  1.   2.   3. -99.]
相关问题