Python Pandas - 计算索引符并在没有完全匹配的情况下查找最接近的索引值
要计算索引符并在没有完全匹配的情况下查找最接近的索引值,请使用 index.get_indexer() 方法。还要将 method 参数设置为 nearest。
首先,导入必需的库 −
import pandas as pd
创建 Pandas 索引 −
index = pd.Index([10, 20, 30, 40, 50, 60, 70])
显示 Pandas 索引 −
print("Pandas Index...\n",index)使用 "get_indexer 計算索引符和蒙版。使用 "method" 参数查找没有完全匹配的情况下最接近的索引值。值设置为 "nearest" −
print("\nGet the indexes...\n",index.get_indexer([30, 25, 58, 50, 69], 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)
# Compute indexer and mask using the "get_indexer"
# Find the nearest index value if no exact match using the "method" parameter.
# The value is set "nearest"
print("\nGet the indexes...\n",index.get_indexer([30, 25, 58, 50, 69], method="nearest"))输出
这将生成如下输出 −
Pandas Index... Int64Index([10, 20, 30, 40, 50, 60, 70], dtype='int64') Number of elements in the index... 7 Get the indexes... [2 2 5 4 6]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP