簡體   English   中英

根據多個條件篩選 pandas DataFrame 列返回空 dataframe

[英]Filter pandas DataFrame column based on multiple conditions returns 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)

如果我用值替換變量 user_ID_existing 和 user_Category_existing,我就會得到這些行。 我什至嘗試使用 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總是返回一個字符串,但由於 pandas 讀取的列ID有一個數字 dtype,當你用一個字符串過濾它時,你會得到一個空的 dataframe。

您需要使用int將值/ID(由用戶輸入)轉換為number

嘗試這個:

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