Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace empty values of a dictionary with NaN

I have a dictionary with missing values (the key is there, but the associated value is empty). For example I want the dictionary below:

dct = {'ID':'', 'gender':'male', 'age':'20', 'weight':'', 'height':'5.7'}

to be changed to this form:

dct = {'ID':NaN, 'gender':'male', 'age':'20', 'weight':NaN, 'height':'5.7'}

How can I write that in the most time-efficient way?

like image 635
user9439906 Avatar asked Mar 11 '18 21:03

user9439906


1 Answers

You can use a dictionary comprehension. Also as was noted in the comments, naming something dict in Python is not good practice.:

dct = {'ID':'', 'gender':'male', 'age':'20', 'weight':'', 'height':'5.7'}
dct = {k: None if not v else v for k, v in dct.items() }
print(dct)

Output:

{'ID': None, 'gender': 'male', 'age': '20', 'weight': None, 'height': '5.7'}

Just replace None with whatever you want it to default to.

In your question, you want to replace with NaN.

You can use any of the following:

float('nan') if you are using Python 2.x, or with Python <3.5

math.nan for Python 3.5+

numpy.nan using numpy

like image 50
user3483203 Avatar answered Oct 16 '22 07:10

user3483203