-1

I'm trying to make a third list which is a intersection of 2 list(This lists I got from pandas dataframe). Now for list2 it is of float and first one is integer and now if I try to compare them third one will be empty one. I tried to convert list2 into integer but that's throwing an error for NaN ("cannot convert float NaN to integer"). Now how to convert that list2 into a list of integers?

Here's the snapshot of second list.List2

And Here's my code:

def intersection(lst1, lst2):
    lst3 = [value for value in lst1 if value in lst2]
    return lst3

list1_NY = df.New_york.values.tolist()
list2_NY = df.NY_11220.values.tolist()
list2_NY = [int(x) for x in list2_NY]
com_list_NY = intersection(list1_NY, list2_NY)
joanis
  • 10,635
  • 14
  • 30
  • 40
  • First you have to decide what you want to do with the NaN values. – Code-Apprentice Apr 13 '21 at 20:30
  • Can you show the code you tried? – joanis Apr 13 '21 at 20:32
  • 1
    And not just NaN values. More generally, are you going to handle non-integer values with round, floor, or ceil? Clamp out-of-range values to INT_MIN and INT_MAX or treat them as invalid? – Howlium Apr 13 '21 at 20:34
  • always put code, data and full error message as text (not screenshot, not link) in question (not comment). – furas Apr 13 '21 at 21:28
  • I want to remove all NaN values @Code-Apprentice . – Darshil Shah Apr 13 '21 at 23:39
  • @joanis here's code :' def intersection(lst1, lst2): lst3 = [value for value in lst1 if value in lst2] return lst3 list1_NY = df.New_york.values.tolist() list2_NY = df.NY_11220.values.tolist() list2_NY = [int(x) for x in list2_NY] com_list_NY = intersection(list1_NY, list2_NY) ' – Darshil Shah Apr 13 '21 at 23:44
  • 1
    Please edit the code into the question, using code block formatting, so we can read it. – joanis Apr 14 '21 at 13:21
  • I just answered your question, but it should probably be marked as a duplicate of [How can I check for NaN values?](https://stackoverflow.com/q/944700/3216427), which is where I found the `math.isnan(x)` solution. – joanis Apr 14 '21 at 14:27
  • 1
    Does this answer your question? [How can I check for NaN values?](https://stackoverflow.com/questions/944700/how-can-i-check-for-nan-values) – joanis Apr 14 '21 at 14:30

1 Answers1

0

You can use math.isnan(x) (see How can I check for NaN values) to detect and filter out the NaNs from list 2:

import math

def intersection(lst1, lst2):
    lst3 = [value for value in lst1 if value in lst2]
    return lst3

#list1_NY = df.New_york.values.tolist()
list1_NY = [123, 567]
#list2_NY = df.NY_11220.values.tolist()
list2_NY = [123.0, 234.0, float('NaN')]
list2_NY = [int(x) for x in list2_NY if not math.isnan(x)]
com_list_NY = intersection(list1_NY, list2_NY)

print(com_list_NY)

outputs [123], which is correct given the values I hard-coded.

joanis
  • 10,635
  • 14
  • 30
  • 40