Skip to content Skip to sidebar Skip to footer

Normalize Array In Python

I have an array ar= [2, 3, 45 , 5556, 6, 'empty', 4] I'd like to normalize this array in order to plot it later. 0:2 1:3 2:45 3: 5556 4: 6 5: 0 # not 'empty' anymore 6: 4 newA

Solution 1:

This works:

ar = [2, 3, 45, 5556, 6, 'empty', 4]
new_ar = [0 if x == 'empty' else x for x in ar]

yields:

[2, 3, 45, 5556, 6, 0, 4]

I used the Python ternary operator at the front of the list comprehension, instead of after.

Edit: If you need a set, as per comment, then simply use {} instead of [] in your comprehension:

new_ar = {0 if x == 'empty' else x for x in ar}

This will automatically ensure unique values only.

Solution 2:

In [91]: ar = [2, 3, 45, 5556, 6, 'empty', 4]

In [92]: [i ifnotisinstance(i, str) else0for i in ar]
Out[92]: [2, 3, 45, 5556, 6, 0, 4]

OR

In[93]: [i if i!='empty' else 0 for i in ar]Out[93]: [2, 3, 45, 5556, 6, 0, 4]

Based on your updated post, this should handle the appropriate removal of duplicates:

In [105]: d = {n if n!='empty'else0:i for i,n inenumerate(ar)}

In [106]: newList = [None]*len(d)

In [107]: for n,i in d.iteritems(): newList[i] = n

In [108]: newList
Out[108]: [2, 3, 45, 5556, 6, 0, 4]

Post a Comment for "Normalize Array In Python"