Python Pandas - 獲取指定標籤的整數位置,並在沒有精確匹配時查詢最近的索引值


要獲取指定標籤的整數位置,並在沒有精確匹配時查詢最近的索引值,可以使用 **index.get_loc()**。將 **method** 引數值設定為 **nearest**。

首先,匯入所需的庫:

import pandas as pd

建立 Pandas 索引:

index = pd.Index([10, 20, 30, 40, 50, 60, 70])

顯示 Pandas 索引:

print("Pandas Index...\n",index)

如果找不到精確匹配,則獲取最近索引值的位置。使用 get_loc() 方法的 "method" 引數將值設定為 "nearest"。

print("\nGet the location of the nearest index if no exact match...\n", index.get_loc(58, method="nearest"))

示例

以下是程式碼:

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 nearest index value if no exact match
# The value is set "nearest" using the "method" parameter of the get_loc()
print("\nGet the location of the nearest index if no exact match...\n", index.get_loc(58, method="nearest"))

輸出

這將產生以下輸出:

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 nearest index if no exact match...
5

更新於:2021年10月14日

169 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.