Python Pandas – 获取所需标签的整数位置并在没有精确匹配时找到前一个索引值

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

# 创建 Pandas 索引
index = pd.Index([10, 20, 30, 40, 50, 60, 70])

# 显示 Pandas 索引
print("Pandas Index...\n",index)

# 返回索引中元素的数量
print("\nNumber of elements in the index...\n",index.size)

# 从给定的索引中获取整数位置
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_loc() 的 method 参数将值设置为 "ffill"
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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程