Python Pandas - 檢查索引是否有重複的值


要檢查索引是否有重複的值,請在 Pandas 中使用 index.has_duplicates 屬性。

首先,匯入所需的庫 −

import pandas as pd

建立索引 −

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

顯示索引 −

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

檢查索引是否有重複值 −

print("\nIs the Pandas index having duplicate values?\n",index.has_duplicates)

例子

以下為程式碼 −

import pandas as pd

# Creating the index
index = pd.Index(['Car','Bike','Truck','Car','Airplane'])

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

# Return an array representing the data in the Index
print("\nArray...\n",index.values)

# Check if the index is having duplicate values
print("\nIs the Pandas index having duplicate values?\n",index.has_duplicates)

輸出

這將產生以下程式碼 −

Pandas Index...
Index(['Car', 'Bike', 'Truck', 'Car', 'Airplane'], dtype='object')

Array...
['Car' 'Bike' 'Truck' 'Car' 'Airplane']

Is the Pandas index having duplicate values?
True

更新於: 2021-10-13

4K+ 瀏覽量

開啟你的 事業

完成課程以獲取證書

立即開始
廣告
© . All rights reserved.