Pandas: วิธีลบรายการที่ซ้ำกันโดยยังคงรักษาแถวด้วยค่าสูงสุด
คุณสามารถใช้วิธีการต่อไปนี้เพื่อลบรายการที่ซ้ำกันใน DataFrame ของแพนด้า แต่เก็บแถวที่มีค่าสูงสุดไว้ในคอลัมน์ใดคอลัมน์หนึ่ง:
วิธีที่ 1: ลบรายการที่ซ้ำกันในคอลัมน์และเก็บแถวไว้ด้วย Max
df. sort_values (' var2 ', ascending= False ). drop_duplicates (' var1 '). sort_index ()
วิธีที่ 2: ลบรายการที่ซ้ำกันในหลายคอลัมน์และเก็บแถวไว้สูงสุด
df. sort_values (' var3 ', ascending= False ). drop_duplicates ([' var1 ', ' var2 ']). sort_index ()
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติ
ตัวอย่างที่ 1: ลบรายการที่ซ้ำกันในคอลัมน์และเก็บแถวไว้ด้วย Max
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีข้อมูลเกี่ยวกับคะแนนที่ผู้เล่นบาสเก็ตบอลจากทีมต่างๆ ทำไว้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ' points ': [20, 24, 28, 30, 14, 19, 29, 40, 22]}) #view DataFrame print (df) team points 0 to 20 1 to 24 2 to 28 3 B 30 4 B 14 5 B 19 6 C 29 7 C 40 8 C 22
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อลบแถวที่มีชื่อ ทีม ซ้ำกัน แต่เก็บแถวที่มีค่าสูงสุดไว้เป็น คะแนน :
#drop duplicate teams but keeps row with max points
df_new = df. sort_values (' points ', ascending= False ). drop_duplicates (' team '). sort_index ()
#view DataFrame
print (df_new)
team points
2 to 28
3 B 30
7 C 40
แต่ละแถวที่มีชื่อ ทีม ซ้ำกันจะถูกลบออก แต่แถวที่มีค่า คะแนน สูงสุดจะยังคงอยู่สำหรับแต่ละ ทีม
ตัวอย่างที่ 2: ลบรายการที่ซ้ำกันในหลายคอลัมน์และเก็บแถวไว้ด้วย Max
สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], ' position ': ['G', 'G', 'F', 'G', 'F', 'F', 'G', 'G', 'F'], ' points ': [20, 24, 28, 30, 14, 19, 29, 40, 22]}) #view DataFrame print (df) team position points 0 AG 20 1 GA 24 2AF 28 3 BG 30 4 BF 14 5 BF 19 6 GC 29 7 GC 40 8 CF 22
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อลบแถวที่มีชื่อ ทีม และ ตำแหน่ง ที่ซ้ำกัน แต่เก็บแถวที่มีค่าสูงสุดสำหรับ คะแนน :
#drop rows with duplicate team and positions but keeps row with max points
df_new = df. sort_values (' points ', ascending= False ). drop_duplicates ([' team ',' position ']). sort_index ()
#view DataFrame
print (df_new)
team position points
1 GA 24
2AF 28
3 BG 30
5 BF 19
7 GC 40
8 CF 22
ทุกแถวที่มีชื่อ ทีม และ ตำแหน่ง ซ้ำกันจะถูกลบออก แต่แถวที่มีค่า คะแนน สูงสุดจะยังคงอยู่สำหรับแต่ละ ทีม และ ชุดตำแหน่ง
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีลบแถวที่ซ้ำกันใน Pandas
วิธีลบคอลัมน์ที่ซ้ำกันใน Pandas
วิธีนับจำนวนซ้ำในแพนด้า