James M
James M

Reputation: 61

Comparing an inputted value to a column list that has been created by Pandas

I am using Pandas to access a CSV file I have created. I have created a list using the data.name.tolist() function, called "IDs", storing all the ID numbers of the users (currently these ID's are 1-6, but will later become 5 digit numbers), What I wish to do, is to compare the entered ID number with the list of IDs, and provide an output based on whether the entered ID is in the list. What would be the best possible method for doing so?

Cheers

    import csv
    import pandas

    colnames = ['name', 'ID', 'carPass', 'cardLost']
    data = pandas.read_csv('info.csv', names = colnames)
    IDs = data.ID.tolist()

    #Asks the user what their ID Number is
    entry = int(input("What is your id number?")).strip()

    if entry isin IDs:
        print("YES")
    else:
        print("NO")

Edit: CSV Sample

    name,ID,carPass,cardLost
    James,1,yes,no
    Daniel,2,no,no
    Georgia,3,yes,yes
    Norman,4,no,no
    Tom,5,no,no
    Sam,6,yes,no

The only relevant data at the moment are the ID and carPass values.

Upvotes: 0

Views: 69

Answers (1)

David Jaimes
David Jaimes

Reputation: 341

Input file info.csv:

 name,ID,carPass,cardLost
 dog,34,yes,yes
 cat,78,yes,no
 bird,45,no,no
 lizard,84,no,yes

This should be enough of a boolean to find the entries with ID number.

import pandas as pd

df = pd.read_csv("info.csv")
entry = int(input("What is your id number? "))

if entry in df["ID"].tolist():
    print(df[df["ID"] == entry])
else:
    print("No entries with that ID number.")

Upvotes: 2

Related Questions