Replace the zeros in a NumPy integer array with nan

女生的网名这么多〃 提交于 2019-12-21 07:24:06

问题


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]

How to replace zeros in a NumPy array with nan?


回答1:


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.

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.]])


来源:https://stackoverflow.com/questions/27778299/replace-the-zeros-in-a-numpy-integer-array-with-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!