0

Working through my first project in pandas and trying to build a simple program that retrieves the ID's and information from a large CSV.

I'm able to get it working when I print it. However when I try to make it a conditional statement it won't work. Is this because of the way I set the index?

The intent is to input an ID and in return list out all the rows with this ID in the CSV.

import numpy as np
import pandas as pd  

file = PartIdsWithVehicleData.csv

excel = pd.read_csv(file, index_col = "ID", dtype={'ID': "str"})

UserInput = input("Enter a part number: ")
result = (excel.loc[UserInput]) 

#If I print this.... it will work
print(result)

#however when I try to make it a conditional statement it runs my else clause. 

if UserInput in excel:
    print(result)
else:
    print("Part number is not in file.")

#one thing I did notice is that if I find the boolean value of the part number (index) it says false..

print(UserInput in excel)


conrito345
  • 35
  • 6
  • So... What are you asking is why `if UserInput in excel` doesn't behave the same as `excel.loc[UserInput]`? – JNevill Jun 16 '22 at 18:20
  • Bdw this is expected behavior, as you are trying to compare a value with a dataframe which would result in `False`. – teedak8s Jun 16 '22 at 18:32

1 Answers1

0

Is this what you are trying to accomplish? I had to build my own table to help visualize the process, but you should be able to accomplish what you asked with a little tweeking to your own data

df = pd.DataFrame({
    'Part_Number' : [1, 2, 3, 4, 5],
    'Part_Name' : ['Name', 'Another Name', 'Third Name', 'Almost last name', 'last name']
})

user_input = int(input('Please enter part number'))

if user_input in df['Part_Number'].tolist():
    print(df.loc[df['Part_Number'] == user_input])
else:
    print('part number does not exist')
ArchAngelPwn
  • 2,891
  • 1
  • 4
  • 17