Python Pandas – 计算索引器并查找前一个索引值(如果没有完全匹配)
要计算索引器并在没有完全匹配时查找前一个索引值,请使用 index.get_indexer() 方法。还要将 method 参数设置为 ffill 。
首先,导入所需的库−
import pandas as pd
创建Pandas索引−
index = pd.Index([10,20,30,40,50,60,70])
显示Pandas索引−
print("Pandas Index...\n",index)
使用“get_indexer”计算索引器和掩码。 如果没有相匹配的,则使用“method”参数查找前一个索引值。 将值设置为“ffill”−
print("\nGet the indexes...\n",index.get_indexer([30,20,75,80,50,59],method="ffill"))
更多Pandas相关文章,请阅读:Pandas 教程
示例
以下是代码−
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)
# Compute indexer and mask using the "get_indexer"
# Find the previous index value if no exact match using the "method" parameter.
# The value is set "ffill"
print("\nGet the indexes...\n",index.get_indexer([30, 20, 75, 80, 50, 59], method="ffill"))
输出
这将产生以下输出−
Pandas Index...
Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64')
Number of elements in the index...
7
Get the indexes...
[2 1 6 6 4 4]
极客教程