简体   繁体   English

根据多个条件筛选 pandas DataFrame 列返回空 dataframe

[英]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. [dataframe image][1] [1]: https://i.stack.imgur.com/TN9Nd.png 当我根据多个条件过滤它时,我得到空 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.如果我用值替换变量 user_ID_existing 和 user_Category_existing,我就会得到这些行。 I even tried with numpy and only getting empty dataframe我什至尝试使用 numpy 并且只得到空的 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.input总是返回一个字符串,但由于 pandas 读取的列ID有一个数字 dtype,当你用一个字符串过滤它时,你会得到一个空的 dataframe。

You need to use int to convert the value/ID (entered by the user) to a number .您需要使用int将值/ID(由用户输入)转换为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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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