Python 用 nan 替换 NumPy 整数数组中的零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27778299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace the zeros in a NumPy integer array with nan
提问by Heinz
I wrote a python script below:
我在下面写了一个python脚本:
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]
How to replace zeros in a NumPy array with nan?
如何用nan替换NumPy数组中的零?
采纳答案by Alex Riley
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.
np.nan
has type float
:包含它的数组也必须具有此数据类型(或complex
orobject
数据类型),因此您可能需要arr
在尝试分配此值之前进行强制转换。
The error arises because the string value 'nan'
can't be converted to an integer type to match arr
's type.
出现错误是因为字符串值'nan'
无法转换为整数类型以匹配arr
的类型。
>>> arr = arr.astype('float')
>>> arr[arr == 0] = 'nan' # or use np.nan
>>> arr
array([[ nan, 1., 2.],
[ 3., 4., 5.]])