Python - 使用 pandas 根據特定值搜尋 DataFrame


我們可以搜尋 DataFrame 的特定值。使用 iloc 獲取所需值並顯示整行。首先,匯入所需的庫 −

import pandas as pd

建立一個具有 4 列的 DataFrame −

dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250]
})

讓我們搜尋註冊價格為 500 的汽車 −

for i in range(len(dataFrame.Car)):
   if 5000 == dataFrame.Reg_Price[i]:
      indx = i

現在,顯示找到的值 −

dataFrame.iloc[indx]

示例

以下是程式碼 −

import pandas as pd

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 120, 150, 110, 200, 250]
})

print"DataFrame ...\n",dataFrame

# search Car with Registeration Price 500
for i in range(len(dataFrame.Car)):
   if 5000 == dataFrame.Reg_Price[i]:
      indx = i

# display the found value
print"\nSearched DataFrame for the following specific value...\n",dataFrame.iloc[indx]

輸出

這將產生以下輸出 −

DataFrame ...
        Car   Cubic_Capacity   Reg_Price   Units_Sold
0       BMW             2000        7000          100
1     Lexus             1800        1500          120
2     Tesla             1500        5000          150
3   Mustang             2500        8000          110
4  Mercedes             2200        9000          200
5    Jaguar             3000        6000          250

Searched DataFrame for the following specific value...
Car             Tesla
Cubic_Capacity   1500
Reg_Price        5000
Units_Sold        150
Name: 2, dtype: object

更新於: 2021-09-21

1K+ 次瀏覽

生涯開掛

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.