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 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告