Python Pandas - 獲取請求標籤的整數位置,如果未找到精確匹配則查詢前一個索引值
要獲取請求標籤的整數位置,如果未找到精確匹配則查詢前一個索引值,請使用 **index.get_loc()**。將引數 **method** 設定為值 **ffill**。
首先,匯入所需的庫 -
import pandas as pd
建立 Pandas 索引 -
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
顯示 Pandas 索引 -
print("Pandas Index...\n",index)如果未找到精確匹配,則獲取前一個索引的位置。使用 get_loc() 的“method”引數將值設定為“ffill” -
print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))示例
以下是程式碼 -
import pandas as pd
# Creating Pandas index
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
# Display the Pandas index
print("Pandas Index...\n",index)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n",index.size)
# get integer location from the given index
print("\nDisplay integer location from given index...\n",index.get_loc(20))
print("\nDisplay integer location from given index...\n",index.get_loc(50))
# Get the location of the previous index if no exact match
# The value is set "ffill" using the "method" parameter of the get_loc()
print("\nGet the location of the previous index if no exact match...\n", index.get_loc(45, method="ffill"))輸出
這將產生以下輸出 -
Pandas Index... Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64') Number of elements in the index... 7 Display integer location from given index... 1 Display integer location from given index... 4 Get the location of the previous index if no exact match... 3
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP