Python Pandas - 指示除首次出現之外的重複索引值


若要指示除首次出現之外的重複索引值,請使用 index.duplicated().keep 引數與值 first 一起使用。

首先,匯入需要的庫 −

import pandas as pd

建立一個帶有重複項的索引 −

index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])

顯示索引 −

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

指示重複的索引值為 True,首個出現的值除外。將“keep”引數設定為“first” −

print("\nIndicating duplicate values except the first occurrence...\n", index.duplicated(keep='first'))

示例

以下是程式碼 −

import pandas as pd

# Creating the index with some duplicates
index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])

# Display the index
print("Pandas Index with duplicates...\n",index)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# get the dimensions of the data
print("\nGet the dimensions...\n",index.ndim)

# Indicate duplicate index values as True, except the first occurrence
# Set the "keep" parameter as "first"
print("\nIndicating duplicate values except the first occurrence...\n", index.duplicated(keep='first'))

輸出

將生成以下程式碼 −

Pandas Index with duplicates...
Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object')

The dtype object...
object

Get the dimensions...
1

Indicating duplicate values except the first occurrence...
[False False False False True]

更新於: 13-10-2021

186 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.