finding and replacing 'nan' with a number
Asked Answered
S

4

11

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?

Sen answered 3/11, 2015 at 2:57 Comment(2)
Aside: what does print(type(train)) return? Neither lists nor numpy ndarrays have a replace method, so I'm not sure why you're not getting an AttributeError. Is train a pandas Series?Lipchitz
To follow up on @DSM's comment, if train were a pandas dataframe or Series, there's a fillna() method that handles this sort of situation.Genevieve
P
8
>>> 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]
Pearlene answered 3/11, 2015 at 3:0 Comment(0)
C
32

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.])
Constanceconstancia answered 3/11, 2015 at 3:13 Comment(0)
P
8
>>> 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]
Pearlene answered 3/11, 2015 at 3:0 Comment(0)
V
0

This code changes all nan to 3:

y = np.nan_to_num(x) + np.isnan(x)*3

This code changes all 3 to nan:

y = x*(x!=3) + 0/(x!=3)

These methods only work with numpy arrays. Please note that np.nan_to_num(x) always changes nan to 0.

Vadim answered 15/2, 2022 at 22:16 Comment(0)
D
0

The following works with floats, but could not quickly make it with integers... Terveisin Markus

import numpy as np
a=np.array([1,2,3,np.nan])
b=np.nan_to_num(a,nan=3)
print(f"a: {a}")
print(f"b: {b}")

a: [ 1. 2. 3. nan]

b: [1. 2. 3. 3.]

Deify answered 2/1, 2023 at 10:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.