Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nan values in a list of dictionaries

Tags:

python

numpy

Am Trying to print if there is a nan value in a list of dictionaries but failed to do so.

data = [{'A' : 2, 'B' : 'ssss'}, {'A' : 3, 'B' : 'xxx'}, {'A' :nan, 'B' : 'ssss'}]

Code :

for x in data:
    if (x['A']== 2):
        print('two')
    elif (x['A']== np.nan)
        print('null')
    else:
        print('nothing')
like image 341
pylearner Avatar asked Oct 24 '25 05:10

pylearner


1 Answers

You can obtain the dictionary's values using dict.values, in this case we can just map with this method, and check if any values in the returned generator are unequal to themselves, meaning that they are NaN:

from itertools import chain
data = [{'A' : 2, 'B' : 'ssss'}, {'A' : 3, 'B' : 'xxx'}, 
        {'A' :float('nan'), 'B' : 'ssss'}]

any(i!=i for i in chain.from_iterable(map(dict.values, data)))
# True

Or following the logic in your code:

for x in data:
    if (x['A']== 2):
        print('two')
    elif (x['A']!= x['A']):
        print('null')
    else:
        print('nothing')
like image 150
yatu Avatar answered Oct 26 '25 18:10

yatu