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