简体   繁体   中英

Filter pandas DataFrame column based on multiple conditions returns empty dataframe

I am having trouble in filtering databased on a multiple conditions. [dataframe image][1] [1]: https://i.stack.imgur.com/TN9Nd.png When I filter it based on multiple condition, I am getting empty DataFrame.

user_ID_existing = input("Enter User ID:")
print("Available categories are:\n Vehicle\tGadgets")
user_Category_existing = str(input("Choose from the above category:"))
info = pd.read_excel("Test.xlsx")
data = pd.DataFrame(info)
df = data[((data.ID == user_ID_existing) & (data.Category == user_Category_existing))]
print(df)

if I replace the variables user_ID_existing and user_Category_existing with values, I am getting the rows. I even tried with numpy and only getting empty dataframe

filtered_values = np.where((data['ID'] == user_ID_existing) & (data['Category'].str.contains(user_Category_existing)))
print(filtered_values)
print(data.loc[filtered_values])

input always returs a string but since the column ID read by pandas has a number dtype, when you filter it by a string, you're then getting an empty dataframe.

You need to use int to convert the value/ID (entered by the user) to a number .

Try this:

user_ID_existing = int(input("Enter User ID:"))

print("Available categories are:\n Vehicle\tGadgets")
user_Category_existing = input("Choose from the above category:")

data = pd.read_excel("Test.xlsx")

df = data[(data["ID"].eq(user_ID_existing))
          & (data["Category"].eq(user_Category_existing))].copy()

print(df)

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