Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23305

How to convert np.NaN to string in ndarray/list?

$
0
0

I have a simple Python code:

l2 =[4,np.nan, 5.1]a2 = np.array(l2)a3 = np.where(np.isnan(a2), '3.3', a2)a3 = a3.astype(float)print(a3)a3 = np.where(np.isnan(a2), 'x', a2)print(a3)

The code above produce two lines:

[4.  3.3 5.1]['4.0''x''5.1']

My question is how to convert np.NaN to string, but without changes to other values.

There where was numbers should stay like number, but only there where is nan should be new string. Like that:

[4.0 'x' 5.1]

UPDATE:If we can not mix data types in Numpy ndarray, I found new solution:

l2 =[4,np.nan, 5.1, np.nan, 3]a2 = np.array(l2)idxNan = (np.argwhere(np.isnan(l2)))for idx in idxNan:    l2[idx[0]] = 'x'print(l2) 

Code above gave me right output:

[4, 'x', 5.1, 'x', 3]

Viewing all articles
Browse latest Browse all 23305

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>