Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding and replacing 'nan' with a number

I want to replace number 3 instead of all 'nan' in array. this is my code:

train= train.replace("nan",int(3))

But nothing changes in my array. Could u please guide me?

like image 855
Talia Avatar asked Nov 03 '15 02:11

Talia


People also ask

How to replace all-9999 values with Nan?

To replace all -9999 values with NaN, you can do: mintemp (mintemp == -9999) = NaN; If you have Statistics Toolbox, you can then use NANMEAN:

How to replace NaN values in a Dataframe using NumPy?

Steps to replace NaN values: 1 For one column using pandas: df ['DataFrame Column'] = df ['DataFrame Column'].fillna (0) 2 For one column using numpy: df ['DataFrame Column'] = df ['DataFrame Column'].replace (np.nan, 0) 3 For the whole DataFrame using pandas: df.fillna (0) 4 For the whole DataFrame using numpy: df.replace (np.nan, 0)

What is NaN (Not a number)?

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results.

What is Nan in pandas Dataframe?

Replace NaN Values with Zeros in Pandas DataFrame Last Updated : 03 Jul, 2020 NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float.


2 Answers

You can use np.isnan:

import numpy as np
train = np.array([2, 4, 4, 8, 32, np.NaN, 12, np.NaN]) 
train[np.isnan(train)]=3
train

Output:

array([  2.,   4.,   4.,   8.,  32.,   3.,  12.,   3.])
like image 149
Joe T. Boka Avatar answered Oct 23 '22 17:10

Joe T. Boka


>>> import math
>>> train = [10, float('NaN'), 20, float('NaN'), 30]
>>> train = [3 if math.isnan(x) else x for x in train]
>>> train
[10, 3, 20, 3, 30]
like image 29
Raymond Hettinger Avatar answered Oct 23 '22 18:10

Raymond Hettinger