Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the zeros in a NumPy integer array with nan

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?

like image 512
Heinz Avatar asked Jan 05 '15 11:01

Heinz


People also ask

How do I change a value from NP to NaN?

In NumPy, to replace missing values NaN ( np. nan ) in ndarray with other numbers, use np. nan_to_num() or np. isnan() .

Does NumPy support NaN?

In Python, NumPy with the latest version where nan is a value only for floating arrays only which stands for not a number and is a numeric data type which is used to represent an undefined value. In Python, NumPy defines NaN as a constant value.


1 Answers

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.]]) 
like image 106
Alex Riley Avatar answered Sep 22 '22 09:09

Alex Riley