1

I am new to coding and I have trouble figuring out how to replace a string in a python list.

# I have
a = [ 200, "NaN", 230 , 300]

# I want
a = [200, np.nan, 230, 300]

Find and replace the string in the list a.

Using python and numpy:

Is it possible to change the "NaN" to np.nan by using a for-loop?

get the error when trying to calculate with a function:

can't multiply sequence by non-int of type 'float'
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Kilian
  • 13
  • 4

2 Answers2

2

I would do the following:

a = [200, "NaN", 230, 300]

a = [np.nan if x == "NaN" else x for x in a]

Alternatively as @tomjn mentioned in the comments. If you are happy working with a numpy array instead of a list you could use

a = np.array(a, dtype=float)
sev
  • 1,500
  • 17
  • 45
  • Thank you, it worked! Is that possible by not using the "NaN" and instead use the type? like replacing the type str with np.nan? – Kilian Jun 08 '21 at 17:44
  • sure, replace `if x == "NaN"` with `if type(x) is str`. Refer to this post for more detail https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python – sev Jun 08 '21 at 17:46
1

numpy will deal with "NaN" when you create an array with dtype=float

>>> a = [200, "NaN", 230 , 300] 
>>> np.array(a, dtype=float)
array([200.,  nan, 230., 300.])

Presumably this is what you want in the end anyway. If you really want a list then add tolist().

tomjn
  • 5,100
  • 1
  • 9
  • 24