How can I remove Nan from list Python/NumPy

前端 未结 10 1905
挽巷
挽巷 2020-12-04 10:56

I have a list that countain values, one of the values I got is \'nan\'

countries= [nan, \'USA\', \'UK\', \'France\']

I tried to remove it,

10条回答
  •  时光取名叫无心
    2020-12-04 11:32

    The question has changed, so to has the answer:

    Strings can't be tested using math.isnan as this expects a float argument. In your countries list, you have floats and strings.

    In your case the following should suffice:

    cleanedList = [x for x in countries if str(x) != 'nan']
    

    Old answer

    In your countries list, the literal 'nan' is a string not the Python float nan which is equivalent to:

    float('NaN')
    

    In your case the following should suffice:

    cleanedList = [x for x in countries if x != 'nan']
    

提交回复
热议问题