Python Pandas - 从索引中返回标签,如果不存在则返回上一个标签

pythonserver side programmingprogramming更新于 2026/1/3 0:44:17

要从索引中返回标签,如果不存在则返回上一个标签,请使用 Pandas 中的 index.asof() 方法。

首先,导入所需的库 −

import pandas as pd

创建 Pandas 索引 −

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

显示 Pandas 索引 −

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

从索引中返回标签,如果不存在,则返回前一个 −

print("\n从索引中获取标签...\n",index.asof(43))

示例

以下是代码 −

import pandas as pd

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

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

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

# 返回索引中的标签,如果不存在,则返回前一个标签
print("\nGet the label from the index...\n",index.asof(43))

输出

这将产生以下输出 −

Pandas Index...
Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')

索引中的元素数量...
7

Get the label from the index...
40

相关文章


有用资源