用nan替换NumPy整数数组中的零 [英] Replace the zeros in a NumPy integer array with nan

查看:165
本文介绍了用nan替换NumPy整数数组中的零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面写了一个python脚本:

I wrote a python script below:

import numpy as np

arr = np.arange(6).reshape(2, 3)
arr[arr==0]=['nan']
print arr

但是我得到了这个错误:

But I got this error:

Traceback (most recent call last):
  File "C:\Users\Desktop\test.py", line 4, in <module>
    arr[arr==0]=['nan']
ValueError: invalid literal for long() with base 10: 'nan'
[Finished in 0.2s with exit code 1]

如何用nan替换NumPy数组中的零?

How to replace zeros in a NumPy array with nan?

推荐答案

np.nan具有类型float:包含它的数组也必须具有此数据类型(或complexobject数据类型),因此您可能需要在尝试分配此值之前先强制转换arr.

np.nan has type float: arrays containing it must also have this datatype (or the complex or object datatype) so you may need to cast arr before you try to assign this value.

由于字符串值'nan'无法转换为整数类型以匹配arr的类型而出现错误.

The error arises because the string value 'nan' can't be converted to an integer type to match arr's type.

>>> arr = arr.astype('float')
>>> arr[arr == 0] = 'nan' # or use np.nan
>>> arr
array([[ nan,   1.,   2.],
       [  3.,   4.,   5.]])

这篇关于用nan替换NumPy整数数组中的零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆