ในการส่งคืนดัชนีโดยลบค่าที่ซ้ำกันโดยสิ้นเชิง ให้ใช้ index.drop_duplicates() วิธีการ
ขั้นแรก นำเข้าไลบรารีที่จำเป็น -
import pandas as pd
การสร้างดัชนีด้วยรายการที่ซ้ำกัน -
index = pd.Index(['Car','Bike','Airplane','Ship','Airplane'])
แสดงดัชนี -
print("Pandas Index with duplicates...\n",index) ส่งคืนดัชนีพร้อมลบค่าที่ซ้ำกัน พารามิเตอร์ "keep" ที่มีค่า "False" จะลดเหตุการณ์ทั้งหมดสำหรับรายการที่ซ้ำกันแต่ละชุด -
print("\nIndex with duplicate values removed (drops all occurrences)...\n",
index.drop_duplicates(keep = False)) ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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 bytes in the data
print("\nGet the bytes...\n",index.nbytes)
# get the dimensions of the data
print("\nGet the dimensions...\n",index.ndim)
# Return Index with duplicate values removed
# The "keep" parameter with value "False" drops all occurrences for each set of duplicated entries
print("\nIndex with duplicate values removed (drops all occurrences)...\n",
index.drop_duplicates(keep = False)) ผลลัพธ์
สิ่งนี้จะสร้างรหัสต่อไปนี้ -
Pandas Index with duplicates... Index(['Car', 'Bike', 'Airplane', 'Ship', 'Airplane'], dtype='object') The dtype object... object Get the bytes... 40 Get the dimensions... 1 Index with duplicate values removed (drops all occurrences)... Index(['Car', 'Bike', 'Ship'], dtype='object')