Python Pandas - 计算索引和掩码以获取新的索引,即使对于非唯一值对象也是如此


要针对新的索引计算索引器和掩码,即使是非唯一值对象,请使用 index.get_indexer_non_unique() 方法。Python Pandas - 计算新的索引的索引器和掩码,即使对于非唯一值对象也是如此

首先导入必需的库 −

import pandas as pd

使用一些非唯一值创建 Pandas 索引 −

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

显示 Pandas 索引 −

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

计算索引器和掩码。用 -1 标记,因为它不在索引中。这也计算非唯一索引对象值 −

print("\nGet the indexes...\n",index.get_indexer_non_unique([30, 40, 90, 100, 50, 60]))

示例

以下为代码 −

import pandas as pd

# Creating Pandas index with some non-unique values
index = pd.Index([10, 20, 30, 40, 40, 50, 60, 60, 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
# Marked by -1, as it is not in index
# This also computes non-unique Index object values
print("\nGet the indexes...\n",index.get_indexer_non_unique([30, 40, 90, 100, 50, 60]))

输出

这将生成以下输出 −

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

Number of elements in the index...
10

Get the indexes...
(array([ 2, 3, 4, -1, -1, 5, 6, 7, 8], dtype=int64), array([2, 3], dtype=int64))

更新于: 14-Oct-2021

94 次浏览

开启你的 事业

完成课程获取认证

开始吧
广告