简体   繁体   中英

Checking for existence of a value in the dataframe doesn't work

Look at the code below. I have a df and in the first method i simple check for the existence of 'Ankit' in the entire dataframe and this works but the second method does'nt. why?

import pandas as pd

# dictionary with list object in values
details = {
'Name' : ['Ankit', 'Aishwarya', 'Shaurya',
          'Shivangi', 'Priya', 'Swapnil'],
'Age' : [23, 21, 22, 21, 24, 25],
'University' : ['BHU', 'JNU', 'DU', 'BHU', 'Geu', 'Geu'],}
# creating a Dataframe object
df = pd.DataFrame(details, columns = ['Name', 'Age', 'University'],
              index = ['a', 'b', 'c', 'd', 'e', 'f'])

print("Dataframe: \n\n", df)

# check 'Ankit' exist in dataframe or not
if 'Ankit' in df.values :
    print("\nThis value exists in Dataframe")
if 'Ankit' in df['Name']:
    print("\nThis value exists in Dataframe")
else:
    print("not found")

The behavior of in when used directly with a DataFrame is to check if a value exists in it's index

So for example, since a is one of your indexes:

'a' in df['Name']  

Will return True , to check within its values, you need to use the .values attribute:

'Ankit' in df['Name'].values

Will return True .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM