วิธีลบคอลัมน์ที่ซ้ำกันใน pandas (พร้อมตัวอย่าง)


คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อลบคอลัมน์ที่ซ้ำกันในแพนด้า:

 df. T. drop_duplicates (). T

ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ

ตัวอย่าง: ลบคอลัมน์ที่ซ้ำกันใน Pandas

สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:

 import pandas as pd

#create DataFrame with duplicate columns
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   ' points ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' assists ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

df. columns = ['team', 'points', 'points', 'rebounds']

#view DataFrame
df

	team points points rebounds
0 A 25 25 11
1 A 12 12 8
2 A 15 15 10
3 A 14 14 6
4 B 19 19 6
5 B 23 23 5
6 B 25 25 9
7 B 29 29 12

เราสามารถใช้โค้ดต่อไปนี้เพื่อลบคอลัมน์ “จุด” ที่ซ้ำกัน:

 #remove duplicate columns
df. T. drop_duplicates (). T

team points rebounds
0 to 25 11
1 to 12 8
2 to 15 10
3 to 14 6
4 B 19 6
5 B 23 5
6 B 25 9
7 B 29 12

โปรดทราบว่าคอลัมน์ “points” จะถูกลบออกในขณะที่คอลัมน์อื่นๆ ทั้งหมดยังคงอยู่ใน DataFrame

เป็นที่น่าสังเกตว่าโค้ดนี้จะลบคอลัมน์ที่ซ้ำกันแม้ว่าคอลัมน์จะมีชื่อต่างกัน แต่มีค่าเหมือนกันก็ตาม

ตัวอย่างเช่น สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:

 import pandas as pd

#create DataFrame with duplicate columns
df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   ' points ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' points2 ': [25, 12, 15, 14, 19, 23, 25, 29],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

	team points points2 rebounds
0 A 25 25 11
1 A 12 12 8
2 A 15 15 10
3 A 14 14 6
4 B 19 19 6
5 B 23 23 5
6 B 25 25 9
7 B 29 29 12

โปรดทราบว่าคอลัมน์ “points” และ “points2” มีค่าเหมือนกัน

เราสามารถใช้โค้ดต่อไปนี้เพื่อลบคอลัมน์ ‘points2’ ที่ซ้ำกัน:

 #remove duplicate columns
df. T. drop_duplicates (). T

team points rebounds
0 to 25 11
1 to 12 8
2 to 15 10
3 to 14 6
4 B 19 6
5 B 23 5
6 B 25 9
7 B 29 12

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีการใช้งานฟังก์ชันทั่วไปอื่น ๆ ในแพนด้า:

วิธีลบแถวที่ซ้ำกันใน Pandas DataFrame
วิธีลบคอลัมน์ใน Pandas
วิธีแยกคอลัมน์ใน Pandas

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *