Check if multiple values exists in a DataFrame using Python IN operator

Viewed 634

I want to check if three values exists in a dataframe, I am not sure how to put those value in a proper way.

enter image description here

my code will give me a wrong answer plug a future warning.elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison

details = {
    'Name' : ['Tom', 'Lee', 'Sara',
              'Shivangi', 'Priya', 'Swapnil'],
    'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],
}
 
df = pd.DataFrame(details, columns = ['Name',  'University'])

if ['Tom', 'Lee', 'Sara'] in df.values:
    print("\nYes, These values exist in Dataframe")
 
else:
    print("\nNo,value not exists ")

since dataframe contain 'Tom', 'Lee', 'Sara', the answer should be yes.

1 Answers

Scott Boston's credit

if sum((df['Name'] == i).any() for i in ['Tom', 'Lee', 'Sara']) == 3:
    print("\nYes, These values exist in Dataframe")
 
else:
    print("\nNo,value not exists ")
Related